クッキーのパラメータ¶
🌐 Translation by AI and humans
This translation was made by AI guided by humans. 🤝
It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖
You can improve this translation by helping us guide the AI LLM better.
クッキーのパラメータは、QueryやPathのパラメータを定義するのと同じ方法で定義できます。
Cookieをインポート¶
まず、Cookieをインポートします:
from typing import Annotated
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[str | None, Cookie()] = None):
return {"ads_id": ads_id}
🤓 Other versions and variants
from typing import Annotated, Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
Tip
Prefer to use the Annotated version if possible.
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: str | None = Cookie(default=None)):
return {"ads_id": ads_id}
Tip
Prefer to use the Annotated version if possible.
from typing import Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
return {"ads_id": ads_id}
Cookieのパラメータを宣言¶
次に、PathやQueryと同じ構造を使ってクッキーのパラメータを宣言します。
最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます:
from typing import Annotated
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[str | None, Cookie()] = None):
return {"ads_id": ads_id}
🤓 Other versions and variants
from typing import Annotated, Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
Tip
Prefer to use the Annotated version if possible.
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: str | None = Cookie(default=None)):
return {"ads_id": ads_id}
Tip
Prefer to use the Annotated version if possible.
from typing import Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
return {"ads_id": ads_id}
技術詳細
CookieはPathとQueryの「姉妹」クラスです。また、同じ共通のParamクラスを継承しています。
しかし、fastapiからQueryやPath、Cookieなどをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
情報
クッキーを宣言するには、Cookieを使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。
情報
ブラウザがクッキーを特殊な方法で裏側で扱うため、JavaScript から簡単には触れられないことを念頭に置いてください。
/docs の API docs UI に移動すると、path operation のクッキーに関する documentation を確認できます。
しかし、データを 入力 して「Execute」をクリックしても、docs UI は JavaScript で動作するためクッキーは送信されず、値を何も書かなかったかのような error メッセージが表示されます。
まとめ¶
クッキーはCookieを使って宣言し、QueryやPathと同じ共通のパターンを使用する。