Cookie Parameters¶
You can define Cookie parameters the same way you defineQuery andPath parameters.
ImportCookie¶
First importCookie:
fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:Annotated[str|None,Cookie()]=None):return{"ads_id":ads_id}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:str|None=Cookie(default=None)):return{"ads_id":ads_id}DeclareCookie parameters¶
Then declare the cookie parameters using the same structure as withPath andQuery.
You can define the default value as well as all the extra validation or annotation parameters:
fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:Annotated[str|None,Cookie()]=None):return{"ads_id":ads_id}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:str|None=Cookie(default=None)):return{"ads_id":ads_id}Technical Details
Cookie is a "sister" class ofPath andQuery. It also inherits from the same commonParam class.
But remember that when you importQuery,Path,Cookie and others fromfastapi, those are actually functions that return special classes.
Info
To declare cookies, you need to useCookie, because otherwise the parameters would be interpreted as query parameters.
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.
Recap¶
Declare cookies withCookie, using the same common pattern asQuery andPath.







