Python / FastAPI Interview Questions
What is middleware in FastAPI and how do you add custom middleware?
Middleware is a function that runs on every request before it reaches a route handler and on every response before it's sent to the client. FastAPI uses Starlette's middleware system — you can add it with @app.middleware('http') or app.add_middleware().
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
import time
app = FastAPI()
# Custom middleware using decorator
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start = time.time()
response = await call_next(request) # passes request to next handler
duration = time.time() - start
response.headers["X-Process-Time"] = str(duration)
return response
# CORS — allow cross-origin requests (e.g. from a React frontend)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myfrontend.com", "http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# GZip compression for large responses
app.add_middleware(GZipMiddleware, minimum_size=1000)Common built-in middleware:
| Middleware | Purpose |
|---|---|
| CORSMiddleware | Cross-Origin Resource Sharing headers |
| GZipMiddleware | Compress responses above minimum size |
| HTTPSRedirectMiddleware | Redirect HTTP to HTTPS |
| TrustedHostMiddleware | Block requests with invalid Host headers |
| SessionMiddleware | Cookie-based sessions |
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...
