Python / FastAPI Basics 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"}
More Related questions...