Fastapi]APIrouterとPydantic Baseモデル
FastAPI Object & modules
APIRouter
FASTAPI
class」、path operation、tagsなどいずれもAPIRouter
class宣言時に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
-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"})
Reference
この問題について(Fastapi]APIrouterとPydantic Baseモデル), 我々は、より多くの情報をここで見つけました https://velog.io/@crosstar1228/Fastapi-APIRouter와-pydantic-base-modelテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol