Prepare for Your FastAPI Interview: Basic to Advanced Questions
FastAPI is a modern, high-performance Python web framework for building APIs. This comprehensive guide covers 30 essential FastAPI interview questions arranged by difficulty level – from basic concepts for freshers to advanced scenarios for experienced developers. Each question includes clear, practical answers with code examples.
Basic FastAPI Interview Questions (Freshers & 0-1 Year Experience)
1. What is FastAPI and what are its main features?
FastAPI is a modern Python web framework for building APIs with high performance. Its main features include automatic API documentation, data validation using Pydantic, async support, and dependency injection[1][2][3].
2. How do you create a basic FastAPI application?
Create a FastAPI instance and define path operations using decorators. Here’s a basic example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
3. What are path parameters in FastAPI?
Path parameters are variables embedded in the URL path. They are defined using curly braces in the path:
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
4. How do query parameters work in FastAPI?
Query parameters appear after the question mark in URLs. FastAPI automatically extracts them:
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
5. What is automatic documentation in FastAPI?
FastAPI automatically generates interactive API documentation at /docs (Swagger UI) and /redoc based on your type hints and path operations[1][2][3].
6. How do you handle request body in FastAPI?
Use Pydantic models to define and validate request body:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
7. What HTTP methods does FastAPI support?
FastAPI supports all standard HTTP methods: GET, POST, PUT, DELETE, PATCH, OPTIONS, and HEAD using corresponding decorators[2].
8. How do you return different status codes in FastAPI?
Use the status_code parameter in decorators:
from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item():
return {"message": "Item created"}
Intermediate FastAPI Interview Questions (1-3 Years Experience)
9. What is Pydantic and how is it used in FastAPI?
Pydantic is a data validation library using Python type annotations. FastAPI uses it for request/response validation and serialization[1][2][3].
10. How do you implement dependency injection in FastAPI?
Dependencies are functions or classes injected into path operations:
from fastapi import Depends
def common_parameters(q: str = None):
return {"q": q}
@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
return commons
11. What is the difference between sync and async endpoints in FastAPI?
Sync endpoints use regular functions (def), async endpoints use async def. Async endpoints handle I/O operations better for high concurrency[2][5].
12. How do you handle errors and exceptions in FastAPI?
Use HTTPException for specific errors and exception handlers for custom logic:
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
13. What are response models in FastAPI?
Response models define the structure of API responses using Pydantic models:
class ItemOut(BaseModel):
id: int
name: str
@app.post("/items/", response_model=ItemOut)
def create_item(item: Item):
return item
14. How do you implement middleware in FastAPI?
Middleware processes requests before they reach endpoints:
@app.middleware("http")
async def add_process_time_header(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
15. How do you validate file uploads in FastAPI?
Use UploadFile from FastAPI:
from fastapi import File, UploadFile
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read()
return {"filename": file.filename}
Advanced FastAPI Interview Questions (3-6+ Years Experience)
16. How do you implement authentication in FastAPI?
Use OAuth2 with JWT tokens and HTTPBearer:
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import JWTError, jwt
security = HTTPBearer()
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
try:
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
return payload.get("sub")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
17. What is the role of APIRouter in FastAPI?
APIRouter allows organizing code into modules and reusing routes across applications:
from fastapi import APIRouter
router = APIRouter(prefix="/items", tags=["items"])
@router.get("/")
def read_items():
return items
app.include_router(router)
18. How do you implement WebSocket support in FastAPI?
Define WebSocket endpoints using WebSocket and WebSocketDisconnect:
from fastapi import WebSocket, WebSocketDisconnect
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message: {data}")
except WebSocketDisconnect:
print("Client disconnected")
19. How do you create custom exception handlers?
Use add_exception_handler method:
from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
return JSONResponse(
status_code=422,
content={"detail": exc.errors()}
)
20. What are background tasks in FastAPI?
Background tasks run after sending the response:
from fastapi import BackgroundTasks
def write_log(message: str):
with open("log.txt", "a") as log:
log.write(message)
@app.post("/send-notification/")
async def send_notification(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "Notification sent")
return {"message": "Notification sent"}
21. How do you implement rate limiting in FastAPI?
Use slowapi library with dependencies:
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.get("/limited")
@limiter.limit("5/minute")
async def limited_endpoint(request: Request):
return {"message": "Success"}
22. How do you handle database sessions with dependencies?
Create database session dependency:
from sqlalchemy.orm import Session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/")
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = User(**user.dict())
db.add(db_user)
db.commit()
return db_user
23. What are tags and summary in FastAPI path operations?
Tags group endpoints in documentation, summary provides brief descriptions:
@app.get("/users/", tags=["users"], summary="Read all users")
def read_users():
return users
24. How do you implement CORS in FastAPI?
Use CORSMiddleware:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
25. How do you test FastAPI applications?
Use TestClient and pytest:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
26. What is the lifespan event handler in FastAPI?
Lifespan handles startup and shutdown events:
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
print("Startup")
yield
# Shutdown
print("Shutdown")
app = FastAPI(lifespan=lifespan)
27. How do you implement pagination in FastAPI?
Use query parameters with skip and limit:
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 100):
items = await fetch_items(skip=skip, limit=limit)
return {"items": items, "skip": skip, "limit": limit}
28. How do you handle sub-applications in FastAPI?
Mount sub-applications using mount():
from fastapi import FastAPI
subapi = FastAPI()
app = FastAPI()
app.mount("/subapi", subapi)
29. What are security schemes in FastAPI?
Security schemes define authentication methods like HTTPBearer, OAuth2PasswordBearer:
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
30. How do you optimize FastAPI performance at Atlassian scale?
For high-scale environments like Atlassian, use async endpoints, connection pooling, Redis caching, Gunicorn with Uvicorn workers, and database query optimization:
# uvicorn main:app --workers 4 --host 0.0.0.0 --port 8000
# With Redis cache dependency
async def get_cached_data(key: str, db: Session = Depends(get_db)):
cached = await redis.get(key)
if cached:
return json.loads(cached)
data = await fetch_from_db()
await