0
0
FastapiHow-ToBeginner · 3 min read

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 name
  • value: the cookie's value
  • max_age or expires: how long the cookie lasts
  • path: URL path the cookie applies to
  • secure: if true, cookie sent only over HTTPS
  • httponly: 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 Response object to the path function, so set_cookie() cannot be called.
  • Setting cookies after returning the response, which has no effect.
  • Forgetting to set httponly=True for sensitive cookies, risking JavaScript access.
  • Not specifying max_age or expires, 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

ParameterDescriptionExample
keyName of the cookie"session_id"
valueValue stored in the cookie"abc123"
max_ageLifetime in seconds3600
expiresExpiration date/time"Wed, 21 Oct 2025 07:28:00 GMT"
pathURL path cookie applies to"/"
secureSend cookie only over HTTPSTrue
httponlyNot accessible by JavaScriptTrue
samesiteControls 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.