Cookie-Parameter
What is Cookie in FastAPI
In FastAPI, a cookie parameter is used to extract and validate values from the HTTP cookies sent by the client in the request. You can use the Cookie class from fastapi to access these values.
In FastAPI, a cookie parameter is used to extract and validate values from the HTTP cookies sent by the client in the request. You can use the Cookie class from fastapi to access these values.
What Are Cookies?
Cookies are small pieces of data stored on the client side and sent with every HTTP request to the server. They're often used for:
- Session management
- User preferences
- Tracking
Basic Example: Reading a Cookie
from fastapi import FastAPI, Cookie
app = FastAPI()
@app.get("/read-cookie/")
def read_cookie(session_id: str = Cookie(None)):
return {"session_id": session_id}
Cookie(None)makes thesession_idcookie optional.- If the cookie is not present,
session_idwill beNone.
Required Cookie Example
@app.get("/secure/")
def secure_area(auth_token: str = Cookie(...)):
return {"auth_token": auth_token}
...means the cookie is required- If the client doesn't send the
auth_tokencookie, FastAPI returns a 422 error
Cookie Name Conversion
Just like with headers, FastAPI converts underscores to hyphens in cookie names:
@app.get("/check/")
def check_cookie(user_id_cookie: str = Cookie(...)):
return {"user_id_cookie": user_id_cookie}
- This will read a cookie named
user-id-cookiefrom the request.
🧠 Summary
| Parameter Type | Source | Use Case |
|---|---|---|
Path | URL path | Resource identification |
Query | URL query string | Filtering, pagination |
Header | HTTP headers | Metadata, auth |
Cookie | HTTP cookies | Sessions, preferences |
Session Auth with Cookies
- User logs in with credentials (e.g., username/password).
- Server verifies credentials and sets a session cookie (e.g., session_id).
- On subsequent requests, the client automatically sends the cookie.
- Server reads the cookie and validates the session.
To use cookies for session authentication in FastAPI, you typically follow this flow:
Code Basic Session Auth with Cookies
from fastapi import FastAPI, Response, Cookie, HTTPException, status
app = FastAPI()
# Simulated session store
fake_session_store = {}
@app.post("/login")
def login(response: Response, username: str, password: str):
if username == "admin" and password == "secret":
session_id = "abc123" # In real apps, generate securely
fake_session_store[session_id] = username
response.set_cookie(key="session_id", value=session_id, httponly=True)
return {"message": "Logged in"}
raise HTTPException(status_code=401, detail="Invalid credentials")
@app.get("/profile")
def get_profile(session_id: str = Cookie(None)):
if session_id in fake_session_store:
return {"username": fake_session_store[session_id]}
raise HTTPException(status_code=401, detail="Invalid or missing session")
@app.post("/logout")
def logout(response: Response, session_id: str = Cookie(None)):
if session_id in fake_session_store:
del fake_session_store[session_id]
response.delete_cookie("session_id")
return {"message": "Logged out"}
Key Points
response.set_cookie(...): sets the cookie on loginCookie(...): reads the cookie from incoming requestsresponse.delete_cookie(...): removes the cookie on logouthttponly=True: prevents JavaScript access to the cookie (for security)
In Real Applications
- Use secure, random session IDs
- Store sessions in a database or Redis
- Set
secure=Truefor HTTPS-only cookies - Consider using JWT if you prefer stateless auth
JWT in Cookies
- User logs in → server generates a JWT token
- Server sets the JWT in an HTTP-only cookie
- On future requests, the client sends the cookie automatically
- Server reads the cookie, verifies the JWT, and authenticates the user
Example Code
from fastapi import FastAPI, Depends, HTTPException, status, Response, Cookie
from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import Optional
app = FastAPI()
# Secret key and algorithm
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Dummy user
fake_user = {"username": "admin", "password": "secret"}
# Create JWT token
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
# Login route
@app.post("/login")
def login(response: Response, username: str, password: str):
if username != fake_user["username"] or password != fake_user["password"]:
raise HTTPException(status_code=401, detail="Invalid credentials")
access_token = create_access_token(data={"sub": username})
response.set_cookie(
key="access_token",
value=access_token,
httponly=True,
secure=False, # Set to True in production with HTTPS
samesite="lax"
)
return {"message": "Logged in"}
# Dependency to get current user from cookie
def get_current_user(access_token: Optional[str] = Cookie(None)):
if not access_token:
raise HTTPException(status_code=401, detail="Missing token")
try:
payload = jwt.decode(access_token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
return {"username": username}
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
# Protected route
@app.get("/profile")
def read_profile(user: dict = Depends(get_current_user)):
return {"user": user}
# Logout route
@app.post("/logout")
def logout(response: Response):
response.delete_cookie("access_token")
return {"message": "Logged out"}
Key Features
- JWT is stored in a secure, HTTP-only cookie
- No localStorage or JavaScript access to the token
- Automatic cookie handling by the browser
- Stateless: no server-side session storage needed