FastAPI Post Request BaseModel - 14

2022. 12. 22. 10:02·Develop/FastAPI
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의 데이터 확인
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
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI Data Validation(추가) - 16
  • FastAPI Fields / Data Validation - 15
  • FastAPI BaseModel 생성 - 13
  • FastAPI Path / Query Parameters 정리 - 12
동석해요
동석해요
공부하고 싶은게 많은, 사소한 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 Post Request BaseModel - 14
상단으로

티스토리툴바