728x90
SMALL
1. BaseModel 생성
from fastapi import FastAPI
from pydantic import BaseModel
from uuid import UUID
app = FastAPI()
class Book(BaseModel):
id: UUID
title: str
author: str
description: str
rating: int
BOOKS = []
@app.get("/")
async def read_all_books():
return BOOKS
2. Post BaseModel 생성
- 매개변수 book은 BaseModel이 정의되어있는 Book 클래스를 받음
- BOOKS 빈 list에 추가되는 book값을 list에 append
- 추가되는 book값을 return
@app.post("/")
async def create_book(book: Book):
BOOKS.append(book)
return book
3. Swagger 확인
- Book의 클래스에 정의 되어 있는 Model로 Request body 구성


- Request body의 값을 수정 후 execute

- BOOKS의 데이터 확인

4. 추가적인 부분
- string으로 정의 되어있는 description에 int 10을 넣으면 자동으로 string으로 변환 시켜준다.


5. 에러사항 확인
- 에러코드 422 return(Book 클래스에 생성한 BaseModel에 정의 한것과 다르게 요청을 했기 때문에)

에러가 난 이유?
pydantic을 통해 필드를 자동으로 조회하고 요청에 따른 유효성을 검사한다.
728x90
SMALL
'Develop > FastAPI' 카테고리의 다른 글
FastAPI Data Validation(추가) - 16 (0) | 2022.12.22 |
---|---|
FastAPI Fields / Data Validation - 15 (0) | 2022.12.22 |
FastAPI BaseModel 생성 - 13 (0) | 2022.12.22 |
FastAPI Path / Query Parameters 정리 - 12 (0) | 2022.12.22 |
FastAPI Delete Request - 11 (0) | 2022.12.22 |