FastAPI service with PostgreSQL
A fast, typed task API with automatic docs, async database access and Docker, the modern Python backend stack.
Intermediateβ± 8β12 hoursπͺ 7 stepsPythonFastAPIPostgreSQLDocker
What you'll learn
- βFastAPI routing and Pydantic models
- βDependency injection
- βRunning Postgres in Docker
What you'll build
- βCRUD for tasks with filtering
- βAutomatic Swagger docs at /docs
- βPydantic validation
- βdocker compose up runs everything
Step-by-step guide
- 1
Install
pip install "fastapi[standard]" sqlalchemy psycopg[binary]; run with fastapi dev main.py.
- 2
Schemas
Pydantic models TaskCreate, TaskUpdate, TaskOut (with model_config from_attributes=True).
- 3
Database
SQLAlchemy 2.0 engine and a get_db() dependency that yields a session and closes it.
- 4
Routes
@app.get("/tasks"), post, patch, delete using Depends(get_db); return 404 with HTTPException.
- 5
Filtering
Query parameters done: bool | None = None and q: str | None = None, applied to the select statement.
- 6
Docker
Dockerfile from python:3.12-slim; docker-compose.yml with the API and postgres:16 and a volume.
- 7
Tests
Use FastAPI TestClient with a test database and override get_db.
π Make it stand out
- +Async SQLAlchemy
- +Background jobs
- +Auth with OAuth2 password flow