Python / FastAPI Interview Questions
How do you read HTTP headers and cookies in FastAPI?
FastAPI provides Header() and Cookie() parameter types. Headers are automatically converted from HTTP's hyphen-case to Python's snake_case. You can also set cookies on responses.
from fastapi import FastAPI, Header, Cookie, Response
from typing import Annotated
app = FastAPI()
# Read request headers
@app.get("/headers")
def read_headers(
user_agent: Annotated[str | None, Header()] = None,
accept_language: Annotated[str | None, Header()] = None,
x_api_key: Annotated[str | None, Header()] = None, # X-Api-Key header
):
# FastAPI converts Accept-Language → accept_language automatically
return {
"user_agent": user_agent,
"accept_language": accept_language,
"x_api_key": x_api_key,
}
# Duplicate headers → list
@app.get("/multi-header")
def multi_header(
x_token: Annotated[list[str] | None, Header()] = None,
):
return {"x_token": x_token} # all values of X-Token header
# Read cookies
@app.get("/profile")
def read_profile(
session_id: Annotated[str | None, Cookie()] = None,
):
return {"session_id": session_id}
# Set a cookie in the response
@app.post("/login")
def login(response: Response, username: str):
response.set_cookie(
key="session_id",
value=f"session_{username}",
httponly=True, # not accessible via JS
secure=True, # HTTPS only
samesite="lax", # CSRF protection
max_age=3600, # 1 hour
)
return {"message": "Logged in"}
# Delete a cookie
@app.post("/logout")
def logout(response: Response):
response.delete_cookie("session_id")
return {"message": "Logged out"}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
