FastAPI interview question · Most asked
How do you test FastAPI applications?
Summary
Use TestClient (sync, based on httpx) or httpx.AsyncClient with ASGITransport for async tests, override dependencies (DB, auth, settings) with app.dependency_overrides, and use pytest fixtures for setup.
Longer Answer
For DB tests, run each test in a transaction that is rolled back, or use a disposable test database (e.g., Testcontainers). Wrap TestClient(app) in a with block to trigger lifespan events. Test both happy paths and validation errors (422), and use pytest-asyncio or anyio for async tests.
Code Example
from fastapi.testclient import TestClient
def fake_user():
return User(id=1, email="[email protected]", role="admin")
def test_reports_requires_admin():
app.dependency_overrides[get_current_user] = fake_user
with TestClient(app) as client:
r = client.get("/reports")
assert r.status_code == 200
app.dependency_overrides.clear()
Key Points
TestClient(app)in awithblock runs lifespandependency_overridesto swap DB/authhttpx.AsyncClient(transport=ASGITransport(app))for async- Isolated DB per test
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?