FastAPI Fields / Data Validation - 15

2022. 12. 22. 10:24·Develop/FastAPI
728x90
SMALL

1. pydantic 라이브러리의 Field를 import

from pydantic import BaseModel, Field

 

2. BaseModel을 정의한 클래스에 Field를 추가

class Book(BaseModel):
    id: UUID
    title: str = Field(min_length=1) #최소길이가 1
    author: str
    description: str
    rating: int

​

3. Swagger 확인

  • 최소길이 1인 title에 빈 값을 return해주니 유효성 검사에서 에러발생
 

4. BaseModel을 정의한 클래스에 Field를 추가

class Book(BaseModel):
    id: UUID
    title: str = Field(min_length=1)
    author: str
    description: str = Field(title="Description of the book",
                             max_length=100,
                             min_length=1)
    rating: int
  • 최소길이 1이고 최대길이가 100인 description에 빈 값을 return해주니 유효성 검사에서 에러발생
 

5. 유효성 검사 오류 확인

  • FastAPI의 강력한 기능인 Schemas에서 확인
  • Book: 사전에 생성했던 BaseModel 클래스
  • HTTPValidationError: http 유효성 검사 오류
  • ValidationError: 유효성 검사 오류

​

6. 선택적 Field 사용해보기

  • 쿼리 매개변수 처럼 옵션 추가하는 방식과 동일하게 Optional을 사용한다.
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field
from uuid import UUID

app = FastAPI()

class Book(BaseModel):
    id: UUID
    title: str = Field(min_length=1)
    author: str
    description: Optional[str] = Field(title="Description of the book",
                             max_length=100,
                             min_length=1)
    rating: int
  • description을 지우고 요청해도 에러 없이 Code 200을 받을 수 있다.
 
 
728x90
SMALL
저작자표시 비영리 변경금지 (새창열림)

'Develop > FastAPI' 카테고리의 다른 글

FastAPI API 없이 값 추가하기 - 17  (0) 2022.12.22
FastAPI Data Validation(추가) - 16  (0) 2022.12.22
FastAPI Post Request BaseModel - 14  (0) 2022.12.22
FastAPI BaseModel 생성 - 13  (0) 2022.12.22
FastAPI Path / Query Parameters 정리 - 12  (0) 2022.12.22
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI API 없이 값 추가하기 - 17
  • FastAPI Data Validation(추가) - 16
  • FastAPI Post Request BaseModel - 14
  • FastAPI BaseModel 생성 - 13
동석해요
동석해요
공부하고 싶은게 많은, 사소한 IT 지식들 공유
    250x250
  • 동석해요
    개발로 자기계발
    동석해요
  • 전체
    오늘
    어제
    • 분류 전체보기 (226)
      • Develop (126)
        • 기초지식 (12)
        • FastAPI (102)
        • Django (11)
      • Database & Data (62)
        • 기초지식 (16)
        • MySQL (29)
        • PostgreSQL (8)
        • 데이터 분석 (9)
      • 인공지능 (11)
        • PyTorch (9)
      • Cloud (8)
        • AWS (4)
        • GCP (2)
      • 버그처리 (14)
      • 회고 & 일상 (5)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
동석해요
FastAPI Fields / Data Validation - 15

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.