Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Cookie Parameter Models

If you have a group ofcookies that are related, you can create aPydantic model to declare them. 🍪

This would allow you tore-use the model inmultiple places and also to declare validations and metadata for all the parameters at once. 😎

Note

This is supported since FastAPI version0.115.0. 🤓

Tip

This same technique applies toQuery,Cookie, andHeader. 😎

Cookies with a Pydantic Model

Declare thecookie parameters that you need in aPydantic model, and then declare the parameter asCookie:

fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIfrompydanticimportBaseModelapp=FastAPI()classCookies(BaseModel):session_id:strfatebook_tracker:str|None=Nonegoogall_tracker:str|None=None@app.get("/items/")asyncdefread_items(cookies:Annotated[Cookies,Cookie()]):returncookies
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportCookie,FastAPIfrompydanticimportBaseModelapp=FastAPI()classCookies(BaseModel):session_id:strfatebook_tracker:str|None=Nonegoogall_tracker:str|None=None@app.get("/items/")asyncdefread_items(cookies:Cookies=Cookie()):returncookies

FastAPI willextract the data foreach field from thecookies received in the request and give you the Pydantic model you defined.

Check the Docs

You can see the defined cookies in the docs UI at/docs:

Info

Have in mind that, asbrowsers handle cookies in special ways and behind the scenes, theydon't easily allowJavaScript to touch them.

If you go to theAPI docs UI at/docs you will be able to see thedocumentation for cookies for yourpath operations.

But even if youfill the data and click "Execute", because the docs UI works withJavaScript, the cookies won't be sent, and you will see anerror message as if you didn't write any values.

Forbid Extra Cookies

In some special use cases (probably not very common), you might want torestrict the cookies that you want to receive.

Your API now has the power to control its owncookie consent. 🤪🍪

You can use Pydantic's model configuration toforbid anyextra fields:

fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIfrompydanticimportBaseModelapp=FastAPI()classCookies(BaseModel):model_config={"extra":"forbid"}session_id:strfatebook_tracker:str|None=Nonegoogall_tracker:str|None=None@app.get("/items/")asyncdefread_items(cookies:Annotated[Cookies,Cookie()]):returncookies
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportCookie,FastAPIfrompydanticimportBaseModelapp=FastAPI()classCookies(BaseModel):model_config={"extra":"forbid"}session_id:strfatebook_tracker:str|None=Nonegoogall_tracker:str|None=None@app.get("/items/")asyncdefread_items(cookies:Cookies=Cookie()):returncookies

If a client tries to send someextra cookies, they will receive anerror response.

Poor cookie banners with all their effort to get your consent for theAPI to reject it. 🍪

For example, if the client tries to send asanta_tracker cookie with a value ofgood-list-please, the client will receive anerror response telling them that thesanta_trackercookie is not allowed:

{"detail":[{"type":"extra_forbidden","loc":["cookie","santa_tracker"],"msg":"Extra inputs are not permitted","input":"good-list-please",}]}

Summary

You can usePydantic models to declarecookies inFastAPI. 😎


[8]ページ先頭

©2009-2026 Movatter.jp