Skip to main content
Cookies are small pieces of data stored on the client and sent with every request. FastAPI makes it easy to read and validate cookies using the Cookie() function. Use Cookie() to declare cookie parameters:
Cookie() works similarly to Query() and Path(), but reads values from cookies instead of the URL.

How It Works

When a client makes a request with cookies:
FastAPI extracts the cookie value and passes it to your function. Make cookies required by not providing a default:
Requests without the required cookie will return a 422 validation error.
Make cookies optional with a default value:
Cookie() supports the same validation parameters as Query():
1

String Validation

Use min_length, max_length, pattern for string cookies
2

Numeric Validation

Use gt, ge, lt, le for numeric cookies
3

Documentation

Add title, description, examples for better API docs
Read multiple cookies in the same endpoint:
Use aliases for cookies with special characters:
Cookie names with hyphens or other special characters need aliases since they’re not valid Python identifiers.

Type Conversion

Cookies are automatically converted to the declared type:

Authentication with Cookies

Common pattern for session-based authentication:
Never trust cookie data blindly. Always validate and sanitize:

Setting Cookies in Responses

While Cookie() reads cookies, use Response to set them:
Always set secure cookies with:
  • httponly=True: Prevent JavaScript access
  • secure=True: Only send over HTTPS
  • samesite="lax" or "strict": CSRF protection
All available parameters:
  • Validation: min_length, max_length, pattern, gt, ge, lt, le
  • Documentation: title, description, examples, deprecated
  • Behavior: alias, default, include_in_schema

Common Use Cases

1

Session Management

Store session IDs for authenticated users
2

User Preferences

Save theme, language, or other preferences
3

Analytics

Track user behavior with tracking cookies
4

Shopping Carts

Maintain cart state across requests
5

A/B Testing

Assign users to experiment groups