Cookie() function.
Basic Cookie Parameter
UseCookie() 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:Required Cookie Parameters
Make cookies required by not providing a default:Optional Cookie Parameters
Make cookies optional with a default value:Cookie Validation
Cookie() supports the same validation parameters as Query():
1
String Validation
Use
min_length, max_length, pattern for string cookies2
Numeric Validation
Use
gt, ge, lt, le for numeric cookies3
Documentation
Add
title, description, examples for better API docsMultiple Cookie Parameters
Read multiple cookies in the same endpoint:Cookie Parameter with Alias
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:Cookie() vs Query() vs Header()
Authentication with Cookies
Common pattern for session-based authentication:Secure Cookie Handling
Setting Cookies in Responses
WhileCookie() reads cookies, use Response to set them:
Cookie() Parameters
All available parameters:- Validation:
min_length,max_length,pattern,gt,ge,lt,le - Documentation:
title,description,examples,deprecated - Behavior:
alias,default,include_in_schema
Testing Cookie Endpoints
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
Related Topics
- Header Parameters - Read HTTP headers
- Query Parameters - Read URL parameters
- Request Body - Handle request data