How to Get Cookies in FastAPI: Simple Guide with Examples
In FastAPI, you get cookies by using the
Cookie parameter from fastapi. Declare a function parameter with Cookie and FastAPI will extract the cookie value from the request automatically.Syntax
Use the Cookie function from fastapi to declare a cookie parameter in your path operation function. FastAPI reads the cookie value from the incoming request and passes it to your function.
cookie_name: str = Cookie(default_value)declares a cookie namedcookie_name.- If the cookie is missing,
default_valueis used orNoneif omitted.
python
from fastapi import FastAPI, Cookie app = FastAPI() @app.get("/items/") async def read_cookie(my_cookie: str | None = Cookie(None)): return {"my_cookie": my_cookie}
Example
This example shows a FastAPI app that reads a cookie named token. If the cookie is present, it returns its value; otherwise, it returns null.
python
from fastapi import FastAPI, Cookie from fastapi.responses import JSONResponse app = FastAPI() @app.get("/show-token") async def show_token(token: str | None = Cookie(None)): if token: return {"token": token} return JSONResponse(content={"error": "No token cookie found"}, status_code=404)
Output
GET /show-token with cookie 'token=abc123' returns {"token": "abc123"}
GET /show-token without cookie returns {"error": "No token cookie found"} with 404 status
Common Pitfalls
1. Forgetting to import Cookie from fastapi. Without this import, your code will fail.
2. Using the wrong parameter type. The cookie parameter must be declared with Cookie, not as a normal function argument.
3. Not handling missing cookies. Always provide a default value like None to avoid errors when the cookie is absent.
python
from fastapi import FastAPI app = FastAPI() # Wrong: cookie parameter without Cookie() @app.get("/wrong") async def wrong(cookie_value: str): return {"cookie": cookie_value} # Correct way from fastapi import Cookie @app.get("/right") async def right(cookie_value: str | None = Cookie(None)): return {"cookie": cookie_value}
Quick Reference
Remember these tips when working with cookies in FastAPI:
- Import
Cookiefromfastapi. - Declare cookie parameters with
Cookie(default). - Use
Noneas default to handle missing cookies gracefully. - Cookies are strings; convert if needed.
Key Takeaways
Use the Cookie parameter from fastapi to read cookies in your endpoint functions.
Always import Cookie from fastapi before using it.
Provide a default value like None to handle missing cookies safely.
Cookies are passed as strings; convert them if you need other types.
Avoid declaring cookie parameters as normal function arguments without Cookie().