728x90
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 |