FastAPI

FastAPI is a modern Python web framework for building APIs, built on type hints. You declare request and response shapes as typed Pydantic models, and FastAPI derives validation, serialization, and interactive OpenAPI documentation from them automatically.

It pairs Python's readability with performance close to Node.js and Go (via async support on Starlette and Uvicorn), which made it the default choice for new Python APIs — especially in data and ML teams, where models trained in Python can be served from the same codebase.

TL;DR

Quick Example

A typed CRUD endpoint with automatic validation and documentation:

Send {"email": "not-an-email"} and FastAPI responds with a 422 and a field-level error report — no validation code written.

Core Concepts

Typed Parameters

FastAPI reads the function signature to know where each value comes from and what type it must be:

A request to /items/abc fails with a clear 422 before your code runs.

Pydantic Models

Request bodies are Pydantic models — typed classes with validation rules:

response_model filters output to the declared fields, so internal attributes (password hashes, flags) never leak — the same concern as excessive data exposure in API security.

Dependency Injection

Depends declares reusable requirements. FastAPI resolves them per request and shares the plumbing:

Dependencies compose (a dependency can depend on another), can be applied to whole routers, and are trivially overridable in tests.

Async vs Sync Endpoints

The rule: never call blocking code inside async def — it stalls the event loop for every request. Use an async library (httpx, asyncpg, SQLAlchemy async) or drop async and let the threadpool handle it.

Structuring Larger Apps

APIRouter splits endpoints into modules, mirroring Express routers or Django apps:

Best Practices

Let the Docs Be the Contract

/docs (Swagger UI) and /openapi.json update automatically from your types. Add tags, summary, and response models so the generated API documentation is genuinely useful — and generate typed clients from the OpenAPI schema instead of hand-writing them.

Manage Config with pydantic-settings

Typed, validated configuration — missing required env vars fail at startup, not at 3 a.m.

Test with the Built-In Test Client

Combine with app.dependency_overrides to swap real databases or auth for fakes — see API Testing.

Deploy on Uvicorn Workers

Put it behind Nginx or a cloud load balancer for TLS and buffering, and add rate limiting at the gateway.

FastAPI vs Alternatives

Choose Django when you need the full batteries (ORM, admin, auth); choose FastAPI when the product is the API and you want types, speed, and OpenAPI out of the box.

Common Mistakes

Blocking Calls in Async Endpoints

Returning ORM Objects Without a Response Model

Without response_model, whatever your ORM object serializes to goes over the wire — including columns you never meant to expose. Always declare output schemas.

Doing Heavy CPU Work in Endpoints

Async helps with I/O, not CPU. Model inference or image processing should go to a worker process or background job queue; BackgroundTasks is only for small fire-and-forget work.

FAQ

Is FastAPI production-ready?

Yes — it's used at scale by Microsoft, Uber, Netflix, and most Python ML platforms. The stack underneath (Starlette + Uvicorn + Pydantic) is mature and actively maintained.

FastAPI or Django for a new Python project?

If you need an ORM, admin interface, and user management out of the box, Django. If you're building a JSON API (especially async or ML-serving), FastAPI. Both can coexist — some teams run DRF for the product and FastAPI for high-throughput services.

What ORM do I use with FastAPI?

FastAPI is ORM-agnostic. SQLAlchemy (with its async engine) is the common choice; SQLModel — by FastAPI's author — combines SQLAlchemy and Pydantic into one model class.

Why is it called "fast"?

Two senses: runtime performance (async ASGI stack benchmarks near Node/Go for I/O workloads) and development speed (validation, serialization, and docs generated from type hints).

Does FastAPI replace Flask?

For APIs, largely yes — FastAPI covers Flask's simplicity while adding types, async, validation, and docs. Flask remains fine for small server-rendered apps and teams with existing Flask investment.

Related Topics

References