How to Set Cookies in FastAPI: Simple Guide with Examples
In FastAPI, you set cookies by using the
Response object and its set_cookie() method inside your path operation function. This method lets you specify cookie name, value, and options like expiration or security flags.Syntax
To set a cookie in FastAPI, use the set_cookie() method on a Response object. The main parts are:
key: the cookie's namevalue: the cookie's valuemax_ageorexpires: how long the cookie lastspath: URL path the cookie applies tosecure: if true, cookie sent only over HTTPShttponly: if true, cookie not accessible by JavaScript
python
from fastapi import FastAPI, Response app = FastAPI() @app.get("/setcookie") async def set_cookie(response: Response): response.set_cookie(key="cookie_name", value="cookie_value", max_age=1800, httponly=True) return {"message": "Cookie set"}
Example
This example shows a FastAPI app with a route that sets a cookie named favourite_color with the value blue. The cookie lasts 1 hour and is HTTP-only for security.
python
from fastapi import FastAPI, Response app = FastAPI() @app.get("/set-fav-color") async def set_fav_color(response: Response): response.set_cookie( key="favourite_color", value="blue", max_age=3600, # 1 hour httponly=True ) return {"message": "Favourite color cookie set"}
Output
{"message": "Favourite color cookie set"}
Common Pitfalls
Common mistakes when setting cookies in FastAPI include:
- Not passing the
Responseobject to the path function, soset_cookie()cannot be called. - Setting cookies after returning the response, which has no effect.
- Forgetting to set
httponly=Truefor sensitive cookies, risking JavaScript access. - Not specifying
max_ageorexpires, causing session cookies that disappear on browser close.
python
from fastapi import FastAPI app = FastAPI() # Wrong: No Response parameter, so set_cookie cannot be called @app.get("/wrong") async def wrong_set_cookie(): # This will cause an error or do nothing # response.set_cookie(...) # response undefined return {"message": "No cookie set"} # Right: Pass Response and set cookie before returning from fastapi import Response @app.get("/right") async def right_set_cookie(response: Response): response.set_cookie(key="token", value="abc123", httponly=True) return {"message": "Cookie set correctly"}
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| key | Name of the cookie | "session_id" |
| value | Value stored in the cookie | "abc123" |
| max_age | Lifetime in seconds | 3600 |
| expires | Expiration date/time | "Wed, 21 Oct 2025 07:28:00 GMT" |
| path | URL path cookie applies to | "/" |
| secure | Send cookie only over HTTPS | True |
| httponly | Not accessible by JavaScript | True |
| samesite | Controls cross-site sending | "lax" or "strict" |
Key Takeaways
Use the Response object’s set_cookie() method inside your path function to set cookies.
Always pass Response as a parameter to your route handler to modify headers.
Set httponly=True for sensitive cookies to improve security.
Specify max_age or expires to control cookie lifetime.
Avoid setting cookies after returning the response; set them before returning.