Web services & data access
19 steps in 5 sets of Python.
What a Python web service looks like in practice now. Pydantic models first, because FastAPI's whole trick is that the type annotation is the validation, the documentation and the serialization all at once.
Then routes, dependency injection, and async handlers, followed by SQLAlchemy for the part where the data has to persist. Nineteen steps, and the Encore wires them into a service rather than leaving you with four libraries and no idea how they meet.
Pydantic models
- Pydantic modelsA model validates and coerces on construction, from a class of annotations.
- Field constraintsField carries the bounds, so validation lives with the declaration.
- Validatorsfield_validator for one field, model_validator for the whole object.
- Nested modelsModels inside models, and lists of them, validated all the way down.
- Settings from the environmentOne model for configuration, read from the environment with defaults.
FastAPI routes
- A FastAPI appA decorated function is an endpoint; the return value becomes JSON.
- Path and query parametersAnnotations declare where a value comes from and what type it must be.
- Request bodiesA pydantic model as a parameter means the body is validated for you.
- Errors and status codesHTTPException is how a handler refuses, with the status you choose.
Dependencies & async
- DependenciesDepends injects shared setup, and the framework caches it per request.
- Async endpointsAn async def handler runs on the event loop, so awaits do not block it.
- MiddlewareA middleware wraps every request: timing, headers, logging.
SQLAlchemy
- SQLAlchemy engine and textThe engine owns the connection pool; text() runs plain SQL through it.
- Declarative modelsA mapped class per table, with typed columns.
- SessionsA Session is a unit of work: add, flush, commit or roll back.
- selectThe 2.0 query API: build a select, execute it, read scalars or rows.
- RelationshipsA foreign key plus relationship gives you objects on both sides.
Encore
- api_service.pyA small FastAPI service: models, dependency-injected store, routes, tests.
- sa_store.pyA SQLAlchemy data layer: models, relationships, queries, aggregates.