FastAPI + SQLAlchemy + PostgreSQL
FastAPI with the SQLAlchemy 2.0 ORM, Alembic migrations and PostgreSQL, the Python API stack for teams that want a full unit-of-work ORM behind typed endpoints.
- FastAPI
- SQLAlchemy
- PostgreSQL
- Pydantic
- Python
- Learning curve
- Moderate
- Status
- Actively developed
- Reviewed
- November 2026
- Best for
- Domain-heavy JSON APIs with many related tables
- Services that need complex queries: CTEs, window functions, upserts, JSONB
- Teams that want explicit transactions and a unit-of-work pattern in Python
- Long-lived codebases where schema changes are frequent and must be migrated safely
- Not ideal for
- Content site needing an editorial admin
- Thin proxy or single-table microservice
Overview
FastAPI handles HTTP, validation and OpenAPI generation; SQLAlchemy 2.0 handles the data layer with typed declarative models (Mapped[], mapped_column), a unit-of-work Session and a SQL expression language that can express almost any PostgreSQL query; Alembic manages schema migrations. Compared with a thin driver setup, this combination adds identity-mapped sessions, relationship loading strategies and dialect features such as JSONB, arrays and INSERT ... ON CONFLICT. It suits domain-heavy APIs where the schema and queries are expected to grow.
What's inside
FastAPI is quick to learn; SQLAlchemy is the main investment. Expect to spend time on session lifecycle, 2.0-style querying, async loading rules and Alembic before the stack feels predictable.
FastAPI
Backend
Handles requests, business logic and APIs
Learning: Easy
Status: Active
SQLAlchemy
ORM
Maps code objects to database tables
Learning: Hard
Status: Active
PostgreSQL
Database
Stores and queries the data
Learning: Moderate
Status: Active
Python
Language
The language the code is written in
Learning: Easy
Status: Active
Pydantic
Other
Supporting tool
Learning: Easy
Status: Active
How it works
A FastAPI dependency opens one SQLAlchemy session per request; the handler validates input with Pydantic, queries through the session, commits once, and maps ORM objects back into Pydantic response models.
- 1.
Infrastructure to backend
Uvicorn receives the request; FastAPI resolves dependencies, including a get_session generator that yields an AsyncSession from the engine's connection pool.
- 2.
Backend to other
Pydantic request models validate the body and query parameters before any database work starts.
- 3.
Backend to orm
The handler or a repository function builds select() statements with explicit selectinload/joinedload options and adds or modifies mapped objects in the session.
- 4.
ORM to database
On flush and commit, SQLAlchemy emits parameterised SQL through asyncpg or psycopg 3 inside a single transaction.
- 5.
ORM to other
Loaded ORM objects are converted into Pydantic response models (from_attributes=True), and the dependency closes the session after the response.
Strengths and drawbacks
Strengths
Typed models in SQLAlchemy 2.0
Mapped[int] and mapped_column give models that mypy and pyright understand, and select() returns typed results, so refactors catch column and relationship mistakes before runtime.
SQL expressiveness without dropping to strings
The expression language covers subqueries, CTEs, window functions, lateral joins and PostgreSQL's insert().on_conflict_do_update(), so hard queries stay composable and parameterised.
Explicit loading strategies
selectinload, joinedload and raiseload let you decide per query how relationships load, which makes N+1 problems visible and fixable instead of hidden behind lazy loading.
Mature migration story
Alembic autogenerates migration scripts from model diffs, supports branches and offline SQL generation, and is the same tool used across most of the SQLAlchemy ecosystem.
Drawbacks
Async session pitfalls
Under AsyncSession, touching an unloaded relationship raises MissingGreenlet instead of lazy-loading, and the default expire_on_commit=True expires objects after commit. Teams must set expire_on_commit=False and eager-load deliberately.
Two model layers to keep in sync
SQLAlchemy models and Pydantic schemas describe the same entities twice. SQLModel merges them for simple cases, but larger apps usually keep both and accept mapping code.
Large API surface
Sessions, identity map, flush versus commit, Core versus ORM, and the legacy 1.x Query API still found in tutorials make SQLAlchemy far bigger to learn than FastAPI itself.
Autogenerate is not a reviewer
Alembic autogenerate misses or misreads some changes, such as column renames (seen as drop and add) and some server defaults and constraint changes, so every migration needs human review.
Mixing sync and async code
Calling a sync Session or a blocking library from an async def endpoint blocks the event loop for every request on that worker; pick one model per service and use def endpoints for sync code.
Scores
Editorial ratings out of 10, comparable across every stack in the guide. They are judgement, not benchmarks. How we score
- Speed of building
- 7.4 out of 10, catalog average 7.7
- Ease of learning
- 6.9 out of 10, catalog average 7.2
- Scalability
- 7.4 out of 10, catalog average 7.6
- Performance
- 7.0 out of 10, catalog average 7.5
- Maintainability
- 8.2 out of 10, catalog average 7.2
- Ecosystem
- 8.4 out of 10, catalog average 8.2
- Flexibility
- 8.2 out of 10, catalog average 7.4
How quickly a team ships features
Higher means easier to pick up
How far it grows before a redesign
Speed of the running application
How well the codebase ages
Libraries, hosting, docs and hiring
How many kinds of product it suits
How it scales
Stateless Uvicorn workers scale out easily; total pooled connections (pool_size plus max_overflow, times workers, times replicas) against PostgreSQL's connection limit is the usual first ceiling.
- Starting outMVP and first users
- One container running Uvicorn with a few workers, a small SQLAlchemy pool, Alembic migrations run at deploy, and managed PostgreSQL.
- GrowingReal traffic, a few engineers
- Several replicas behind a load balancer, PgBouncer in transaction mode (with asyncpg's statement cache disabled unless PgBouncer's prepared-statement support is enabled), and a separate read-only engine for reporting endpoints.
- LargeHeavy traffic or data
- Kubernetes autoscaling, routing reads to PostgreSQL replicas through a second session factory, background work moved to a queue, and hot queries tuned with EXPLAIN and Core statements.
- EnterpriseMany teams and regions
- Domain-split services each owning their schema and Alembic history, partitioned tables for large datasets, and an event bus for cross-service data instead of shared tables.
Where it fits
Common projects, from best fit to worst.
B2B domain API with rich relations
Accounts, projects, permissions and audit trails map cleanly to related models, with Alembic tracking every schema change across environments.
Great fit
Data or ML platform backend
Stores datasets, experiment metadata and job state in PostgreSQL while staying in the same Python process as pandas or model-serving code.
Good fit
Thin proxy or single-table microservice
Works, but the ORM, session handling and migrations add more code and per-row overhead than a few hand-written asyncpg queries need.
Workable
Content site needing an editorial admin
There is no built-in admin, auth or templating story; Django or Rails deliver this with far less assembly.
Poor fit
Alternatives
Similar stacks, and when you would choose them instead.
- FastAPI + PostgreSQL
Pick a thinner data layer (raw asyncpg, SQLModel or a query builder) when the service has a handful of tables and you would rather not learn a full ORM.
CompareFastAPI + SQLAlchemy + PostgreSQL with FastAPI + PostgreSQL - Django + PostgreSQL
Pick Django when you want the ORM, migrations, auth and an admin UI decided for you instead of assembling them.
CompareFastAPI + SQLAlchemy + PostgreSQL with Django + PostgreSQL - Flask + PostgreSQL
Flask with Flask-SQLAlchemy uses the same ORM in a synchronous WSGI app, which suits server-rendered pages and teams that do not need async.
CompareFastAPI + SQLAlchemy + PostgreSQL with Flask + PostgreSQL - NestJS + Prisma + PostgreSQL
The TypeScript counterpart: schema-first Prisma models and generated types instead of SQLAlchemy's code-first mapping.
CompareFastAPI + SQLAlchemy + PostgreSQL with NestJS + Prisma + PostgreSQL
Sources
Reviewed on November 19, 2026 against the documentation below. Found something out of date? Suggest a correction. Read our methodology.
- SQLAlchemy 2.0: ORM Quick Start
Official 2.0-style declarative mapping with Mapped[] and select().
- SQLAlchemy: Asynchronous I/O (asyncio)
AsyncSession, AsyncEngine and the lazy-loading restrictions under asyncio.
- Alembic documentation
SQLAlchemy's migration tool, including autogenerate.
- FastAPI: Dependencies with yield
The pattern used for one database session per request.
Related stacks
Stacks that share technologies with FastAPI + SQLAlchemy + PostgreSQL.
Python + FastAPI + PyTorch
PyTorch models served behind a FastAPI HTTP API, a common pattern for custom, small-to-medium scale model inference services.
- Python
- FastAPI
- Pydantic
- +1
Learning: Moderate
Django + Celery + Redis + PostgreSQL
Django web app with Celery workers, Redis as broker and cache, and PostgreSQL as the system of record, the standard way to move slow work out of Django requests.
- Django
- Celery
- Redis
- +2
Learning: Moderate
Python + LangChain
LLM application orchestration in Python with LangChain and LangGraph: retrieval, tool calling and agents over hosted or self-hosted models.
- Python
- LangChain
- Pydantic
Learning: Moderate