Skillversitas

Cookie Parameters

Cookies are small values the server sets on the client and that the browser sends back with every request. FastAPI can read cookies as validated function parameters with the Cookie dependency, just like query parameters.

Reading Cookies

from fastapi import Cookie, FastAPI

app = FastAPI()

@app.get("/items/")
def read_items(
    last_login: str | None = Cookie(default=None),
    user_id: int | None = Cookie(default=None),
):
    return {"last_login": last_login, "user_id": user_id}

A request carrying Cookie: last_login=2026-11-06; user_id=42 gets both values extracted and converted. Missing cookies yield the default (None).

Setting Cookies

Use the Response object's set_cookie method to add a Set-Cookie header to the response:

from fastapi import FastAPI, Response

app = FastAPI()

@app.post("/login/")
def login(response: Response, username: str):
    response.set_cookie(
        key="user_id",
        value=username,
        max_age=60 * 60 * 24,  # one day
        httponly=True,
        samesite="lax",
    )
    return {"message": f"Logged in as {username}"}

Secure Cookie Attributes

  • httponly=True - JavaScript cannot read the cookie (mitigates XSS theft).
  • secure=True - the cookie is only sent over HTTPS.
  • samesite - lax is the sensible default for session cookies; strict for same-site-only flows; none (with secure) for cross-site reads.
  • max_age / expires - controls lifetime.

When to Use Cookies

Cookies suit session identifiers and user preferences. For authentication tokens, consider an Authorization header instead; for CSRF-protected forms, a session cookie plus a same-site policy is the classic pattern.

Summary

Read cookies with Cookie(default=...) parameters, which are validated like query parameters, and set them with response.set_cookie using httponly, secure, and samesite for safety. Use cookies for sessions and preferences, and prefer headers for bearer-token authentication.