Cookie Parameters

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can define Cookie parameters the same way you define Query and Path parameters.

Import Cookie

First import Cookie:

  1. from typing import Optional
  2. from fastapi import Cookie, FastAPI
  3. app = FastAPI()
  4. @app.get("/items/")
  5. async def read_items(ads_id: Optional[str] = Cookie(None)):
  6. return {"ads_id": ads_id}

Declare Cookie parameters

Then declare the cookie parameters using the same structure as with Path and Query.

The first value is the default value, you can pass all the extra validation or annotation parameters:

  1. from typing import Optional
  2. from fastapi import Cookie, FastAPI
  3. app = FastAPI()
  4. @app.get("/items/")
  5. async def read_items(ads_id: Optional[str] = Cookie(None)):
  6. return {"ads_id": ads_id}

Technical Details

Cookie is a “sister” class of Path and Query. It also inherits from the same common Param class.

But remember that when you import Query, Path, Cookie and others from fastapi, those are actually functions that return special classes.

Info

To declare cookies, you need to use Cookie, because otherwise the parameters would be interpreted as query parameters.

Recap

Declare cookies with Cookie, using the same common pattern as Query and Path.