Fastapi]APIrouterとPydantic Baseモデル


FastAPI Object & modules


APIRouter

  • 「miniFASTAPIclass」、path operation、tagsなどいずれも
  • APIRouterclass宣言時にprefix、tags dependencies、responseを予め宣言し、path操作で上記の内容を繰り返さないようにする
  • 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)にマッピングされたタグ.通常は1つのstringとして定義してもよいし、List[str]として定義してもよい
  • dependencies:pathオペレーションのすべてのグループに認証を適用する場合に使用
  • responses-dictobjectを入力として
    -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"})