[Fastapi] APIRouter와 pydantic base model

건너별·2022년 3월 31일
0

fastapi

목록 보기
5/6

FastAPI Object & modules

APIRouter

  • "mini FASTAPI class" 이고, path operation, tagging, 등 모두 가능
  • APIRouter Class 선언 시 prefix, tags dependencies, responses 등 모두 미리 선언하여 path operation에서 같은 내용을 반복하지 않아도 되게 함
from fastapi import APIRouter, Depends, HTTPException

from ..dependencies import get_token_header

# 미리 선언
router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)


fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}


@router.get("/") # 여기에 tags 등 여러번 쓸 필요 없음!
async def read_items():
    return fake_items_db


@router.get("/{item_id}")
async def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
  • tags : Swagger UI(docs)에 매핑되는 태그. 일반적으로 string하나로 정의되고, List[str]으로 정의되기도 함

  • dependencies : path operation의 모든 그룹에 authentication을 적용시킬 때 씀

  • responses
    - dict object를 입력으로 받음
    - key가 status code이고, value가 이에 대한 정보가 담긴 또다른 dict 로 이루어짐

예시)

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel



class Item(BaseModel):
    id: str
    value: str
class Message(BaseModel):
    message: str

app = FastAPI()
# response
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read_item(item_id: str):
     if item_id == "foo":
          return {"id": "foo", "value": "there goes my hero"}
      else:
          return JSONResponse(status_code=404, content={"message": "Item not found"})
profile
romantic ai developer

0개의 댓글