0
0
FastapiHow-ToBeginner · 3 min read

How to Use Cookie in FastAPI: Simple Guide with Examples

In FastAPI, you use the Response.set_cookie() method to send cookies to the client and the Cookie dependency to read cookies from requests. This allows you to store small pieces of data on the user's browser and access them in your API endpoints.
📐

Syntax

To set a cookie in FastAPI, use Response.set_cookie(key, value, options). To read a cookie, use the Cookie dependency in your endpoint parameters.

  • Response.set_cookie: sets a cookie with a name (key) and value (value), plus optional settings like max_age, httponly, and secure.
  • Cookie: a special parameter type that extracts cookie values from incoming requests by cookie name.
python
from fastapi import FastAPI, Response, Cookie

app = FastAPI()

@app.get("/set-cookie")
def set_cookie(response: Response):
    response.set_cookie(key="mycookie", value="cookievalue", max_age=1800, httponly=True)
    return {"message": "Cookie set"}

@app.get("/get-cookie")
def get_cookie(mycookie: str | None = Cookie(default=None)):
    return {"mycookie": mycookie}
💻

Example

This example shows how to set a cookie named username with a value and then read it back in another endpoint.

python
from fastapi import FastAPI, Response, Cookie

app = FastAPI()

@app.get("/login")
def login(response: Response):
    # Set cookie 'username' with value 'alice'
    response.set_cookie(key="username", value="alice", max_age=3600, httponly=True)
    return {"message": "Logged in and cookie set"}

@app.get("/profile")
def profile(username: str | None = Cookie(default=None)):
    if username:
        return {"message": f"Welcome back, {username}!"}
    return {"message": "No username cookie found"}
Output
GET /login -> {"message": "Logged in and cookie set"} GET /profile (with cookie username=alice) -> {"message": "Welcome back, alice!"} GET /profile (without cookie) -> {"message": "No username cookie found"}
⚠️

Common Pitfalls

  • Forgetting to pass Response to the endpoint to set cookies.
  • Not using the Cookie dependency to read cookies, which leads to missing cookie values.
  • Setting cookies without httponly=True when security is important, exposing cookies to JavaScript.
  • Expecting cookies to be immediately available after setting them in the same request (cookies are sent to client and returned on next request).
python
from fastapi import FastAPI, Cookie, Response

app = FastAPI()

# Wrong: Trying to set cookie without Response
@app.get("/wrong-set")
def wrong_set():
    # This does nothing because no Response object to set cookie
    return {"message": "No cookie set"}

# Right: Use Response to set cookie
@app.get("/right-set")
def right_set(response: Response):
    response.set_cookie(key="token", value="abc123")
    return {"message": "Cookie set properly"}
📊

Quick Reference

Remember these key points when working with cookies in FastAPI:

  • Use Response.set_cookie() to send cookies.
  • Use Cookie dependency to read cookies.
  • Set httponly=True for security when appropriate.
  • Cookies are stored on the client and sent back on subsequent requests.

Key Takeaways

Use Response.set_cookie() to set cookies in FastAPI responses.
Use the Cookie dependency to read cookies from incoming requests.
Always pass Response to your endpoint if you want to set cookies.
Set httponly=True on cookies to improve security by restricting JavaScript access.
Cookies set in a response are available in the next client request, not immediately.