FastAPI Service Scaffold
Generate a production-ready FastAPI service with async-first conventions. Keep it clean and testable;
avoid dumping everything in one main.py.
When to use
- "Create/scaffold a FastAPI service/API"
- "Add structure / async DB / health checks / tests to my FastAPI app"
Target layout
<service>/
├── app/
│ ├── main.py # create_app() factory + lifespan
│ ├── config.py # pydantic-settings (env-driven)
│ ├── api/ # routers (versioned, e.g. api/v1/)
│ ├── deps.py # dependencies (db session, auth)
│ ├── db.py # async engine + session factory
│ ├── models/ # SQLAlchemy 2.0 models
│ ├── schemas/ # pydantic request/response models
│ └── observability.py # logging + metrics
├── tests/ # pytest + httpx AsyncClient
├── Dockerfile
├── pyproject.toml
└── README.md
Conventions (apply these)
- App factory —
create_app()wires routers, middleware, and alifespancontext that opens the DB pool on startup and disposes it on shutdown. No module-level side effects. - Settings —
pydantic-settingsBaseSettingsreading env; oneSettingsinstance via a cached dependency. Fail fast on missing required vars. - Async DB — SQLAlchemy 2.0 async engine +
async_sessionmaker; provide anAsyncSessiondependency; one session per request, committed/rolled back at the edge. - Schemas vs models — pydantic schemas for I/O, SQLAlchemy models for persistence; never leak ORM objects directly in responses.
- Health —
GET /healthz(liveness) andGET /readyz(DB ping). Unauthenticated and cheap. - Metrics — Prometheus via
prometheus-fastapi-instrumentatoror custom middleware (RED metrics). - Logging — structured (structlog or stdlib JSON) with a
request_idmiddleware. - Errors — consistent exception handlers returning a uniform error envelope.
- Tests —
pytest+httpx.AsyncClientagainst the app; a fixture for a test DB/session. - Tooling —
ruff(lint+format) andmypy;uvorpip-toolsfor deps; pin versions.
Steps
- Ask for service name and datastores (Postgres assumed; Redis/Kafka optional).
- Generate the layout with an app factory, settings, async DB session dep, health, metrics, and one example router with a schema and a test.
- Add Dockerfile (slim Python multi-stage, non-root) and README with
uvicorn app.main:create_app --factory. - Ensure
pytestandruff checkpass before finishing.
Mirrors go-microservice-scaffold so Go and Python services in the same org feel consistent.