Why this matters
These three frameworks run most Python backends you'll meet. AI services in particular lean on FastAPI (async, typed, streaming-friendly), while many established products run on Django. You should be productive in both and able to explain the trade-off.
The three in one table
| FastAPI | Django (+ DRF) | Flask | |
|---|---|---|---|
| Style | Async-first, typed, minimal | Batteries included | Minimal, sync-first |
| Validation | Pydantic built in | Forms / DRF serializers | Bring your own |
| ORM | Bring your own (SQLAlchemy, SQLModel) | Django ORM + migrations | Bring your own |
| Admin, auth | Bring your own | Built in | Extensions |
| Streaming / SSE | Natural | Possible via ASGI | Possible |
| Best for | APIs, AI gateways, microservices | Products with lots of models, admin, auth | Small services, prototypes |
How a FastAPI service is structured
from contextlib import asynccontextmanager
from typing import Annotated
import httpx
from fastapi import Depends, FastAPI, HTTPException
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=httpx.Timeout(10, connect=3)) # one shared client
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
def get_http(request) -> httpx.AsyncClient: # dependency: easy to override in tests
return request.app.state.http
@app.get("/v1/weather/{city}")
async def weather(city: str, http: Annotated[httpx.AsyncClient, Depends(get_http)]):
r = await http.get(f"https://weather.example/api/{city}")
if r.status_code == 404:
raise HTTPException(404, "Unknown city")
r.raise_for_status()
return r.json()
Key habits: one shared client per external service, created in lifespan (connection reuse); dependencies for anything you'll want to fake in tests; Pydantic models for request and response bodies; layered code (router → service → repository) so business logic doesn't import the web framework.
Django in brief
Request → URL router → view (or DRF viewset) → ORM → template or serializer → response. Strengths: migrations, admin, auth, a huge ecosystem. Watch for:
- N+1 queries: use
select_related(joins) andprefetch_related(separate batched query). - Long work in a sync view blocks a worker. Long model calls go to Celery or an async view (Q11).
- Version pinning: know which release is LTS (5.2 is; 6.0 isn't) when you write it on a CV.
Why this way
Pick by the product, not fashion: an AI gateway or a streaming chat service suits FastAPI; a CRUD-heavy product with an admin and many models suits Django; a two-endpoint internal tool suits either or Flask. A team's existing expertise usually outweighs small technical differences.
Common mistakes
- Creating a new HTTP client per request (no connection reuse, slow, and can exhaust sockets).
- Business logic inside route functions, untestable without HTTP.
- Blocking calls inside
async defroutes.
Interview follow-ups
- "When would you not use FastAPI?" When the product needs Django's admin, auth, ORM migrations and ecosystem on day one, or the team is Django-fluent; framework familiarity beats small technical gains.
- "
async defordeffor a FastAPI route?"async defonly if everything awaited inside is async; otherwise usedef, which FastAPI runs in a thread pool, so a blocking library doesn't freeze the event loop. - "How do you test a route that calls an external API?" Override the dependency that provides the client with a fake (or use
respx), assert on behaviour and error mapping, and keep a separate, small live suite. - "How do you add a long LLM call to a Django view?" Don't hold a sync worker for 30 seconds: enqueue to Celery and poll or push the result, or use an async view with streaming under ASGI.
Check yourself
Why create the HTTP client in lifespan instead of per request?
Connection pooling and TLS session reuse make calls much faster; one client is shared safely across requests and closed cleanly at shutdown.
What's the N+1 problem and how does Django fix it?
Loading a list (1 query) and then a related object for each item (N queries). select_related joins foreign keys into the first query; prefetch_related loads many-to-many or reverse relations in one extra query.
Build it
Build a FastAPI service with one endpoint that calls a public API through a lifespan-managed client, a dependency you override in a pytest test with a fake, and Pydantic response models.