当サイトは、アフィリエイト広告を利用しています
fastapiを使用したREST API実装時にエンドポイントとなる関数の引数で
使われる。
の3つの関数ついて、その目的、構文、使い方をまとめておく。
REST APIや、パスパラメータ、クエリパラメータ、リクエストボディについては下記記事で解説しているので
参照ください
この3つは目的は引数の仕様書を作る関数であり
の役割がある
当記事では1,2の役割についてメインでまとめる
実際の使い方や構文、使用する箇所を実行サンプルを使ってまとめていく。
使用箇所は当記事の冒頭でも書いたように、基本的に
エンドポイント関数の引数内で使用される
※その他で単体で使用されることはない。多分。。
APIにリクエスト来た時にに Pydanticが検証で使う ※FastAPIが定義を解析し、Pydanticが実行時に検証する
リクエストにクエリパラメータがある場合に
fastapiのエンドポイントの関数で引数として受ける時に使う
Query(default,*,alias=None,title=None,description=None,gt=None,ge=None,lt=None,le=None,min_length=None,max_length=None,regex=None,deprecated=False,example=None,examples=None,include_in_schema=True)
from fastapi import Query@app.get("/items")def get_item(name: str = Query(...), price: int = Query(0)):return {"name": name, "price": price}
@app.get("/items")def get_item(name: str, price: int = 0): # 直接引数に指定return {"name": name, "price": price}
リクエストにパスパラメータがある場合に
fastapiのエンドポイントの関数で引数として受ける時に使う
Path(default,*,alias=None,title=None,description=None,gt=None,ge=None,lt=None,le=None,regex=None,example=None,examples=None,deprecated=False,include_in_schema=True)
from fastapi import Path@app.get("/users/{user_id}")def get_user(user_id: int = Path(..., description="ユーザーID", ge=1)):return {"user_id": user_id}
ge=1)が可能@app.get("/users/{user_id}")def get_user(user_id: int): # 型だけ指定return {"user_id": user_id}
リクエストにbodyがある場合に
fastapiのエンドポイントの関数で引数として受ける時に使う
pydanticのBaseModelクラスと併用することが基本
Body(default,*,embed=False,media_type="application/json",alias=None,title=None,description=None,example=None,examples=None,deprecated=False,include_in_schema=True)
from pydantic import BaseModelfrom fastapi import Bodyclass Product(BaseModel):name: strprice: int@app.post("/products")def create_product(product: Product = Body(...)):return product
@app.post("/products")def create_product(product: Product): # Body(...) を省略return product
下記記事で記載
- embedについてNoneを受けれるオプショナルにしたい場合は
にする必要がある。
async def get_users(age: int | None = Query(None, description="ユーザーの年齢でフィルタ")):
class UserUpdate(BaseModel):name: str | None = Noneage: int | None = None
Query(...)Path(...)Body(...)
Query(1)class UserCreate(BaseModel):name: str # 必須age: int | None # 任意
@app.get("/users/{user_id}")def get_user(user_id: int):
q: str = None # 型が None を許可していない
エンドポイントの引数を作るために、先に関数を実行する仕組み
かみ砕くと
を行う
def common_query(q: str | None = Query(None, min_length=1, max_length=50)):return q@app.get("/items")def read_items(q: str = Depends(common_query)):...
流れは
になる
fastapiでよく見る
について詳しく調べたみた。
この前提を持った上で、