FastAPI Interview Questions
Q: What makes FastAPI fast?
Two things: (1) It is built on Starlette (ASGI) and uses async I/O — async route handlers don't block threads on I/O waits. (2) Pydantic v2 uses Rust-based validation (pydantic-core) making serialization/validation extremely fast. FastAPI also generates OpenAPI docs at zero runtime cost (metadata only).
Q: How does FastAPI handle request validation?
FastAPI uses Python type hints and Pydantic models to automatically validate request data. Path parameters, query params, and request body are all validated before the route handler runs. Invalid data returns a 422 Unprocessable Entity with a detailed error list. No manual validation code is needed.
Q: What is the Depends() system?
Depends() is FastAPI's dependency injection system. A dependency is any callable (function or class) whose return value is injected into the route handler. Dependencies can be nested (a dependency can depend on other dependencies), and FastAPI handles their resolution automatically. Common uses: database sessions, auth, pagination parameters, feature flags.
Q: async def vs def in FastAPI routes?
Use async def when the route does I/O (async database calls, HTTP requests, file reads). FastAPI awaits it directly on the event loop. Use def for CPU-bound work — FastAPI automatically runs sync routes in a threadpool executor so they don't block the event loop. Mixing async and sync incorrectly (e.g., calling blocking code in async def) will stall the server.
Q: What is response_model used for?
response_model specifies the Pydantic model for the response, which (1) filters out fields not in the model (e.g., passwords), (2) validates response data, and (3) generates the correct OpenAPI schema for docs. This keeps internal implementation details out of API responses without extra serialization logic.
Q: How do you run FastAPI in production?
# Development
uvicorn main:app --reload --port 8000
# Production — use Gunicorn with Uvicorn workers
gunicorn main:app -k uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8000
# Or with uvicorn directly (single process, use multiple containers for scale)
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 1Q: How do you test FastAPI endpoints?
from fastapi.testclient import TestClient
import pytest
client = TestClient(app)
def test_create_user():
response = client.post("/users", json={"email": "a@b.com", "name": "Alice", "password": "Strong1"})
assert response.status_code == 201
assert response.json()["email"] == "a@b.com"
def test_get_user_not_found():
response = client.get("/users/99999")
assert response.status_code == 404
# Override dependencies in tests
from main import app, get_db
def override_get_db():
yield test_db_session
app.dependency_overrides[get_db] = override_get_dbKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free