Skip to content
Public template

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

FastAPI Service

A production-minded template for independent Python APIs: FastAPI, uv, Ruff, Pyright, pytest, async PostgreSQL with SQLAlchemy, Alembic migrations, structured logs, and a non-root Docker image.

The app starts without database configuration. Public GET / returns service metadata from APP_NAME and APP_VERSION, without accessing the database:

{
  "service": "FastAPI Service",
  "version": "0.1.0",
  "documentation": "/docs"
}

The documentation field is omitted when documentation is disabled (the production default). This identifies the service; it does not report health. Keep this route public when adding authentication to domain endpoints.

GET /healthz is a liveness probe. GET /readyz verifies PostgreSQL only when DATABASE_REQUIRED=true. There are no application tables, example CRUD routes, or authentication; each generated service adds only the domain behavior it needs.

Create a service

On GitHub, use Use this template → Create a new repository, then clone it.

  1. Rename project.name and update description in pyproject.toml.
  2. Update the default app_name and app_version in src/core/config.py and .env.example.
  3. Update this README and choose your service's image/container names.
  4. Run uv lock after changing project metadata; commit the updated lockfile.
  5. Add only the domain modules your service needs.

Generated repositories are independent. Later template changes do not automatically update existing services.

Install and run

Install uv. The project uses Python 3.13; uv can install it when needed. Run from the repository root:

uv sync --locked
uv run uvicorn src.main:app --reload --port 8000

Use another free host port if 8000 is already occupied. Stop with Ctrl+C. No .env or database is needed for the health endpoint.

Configuration

Optionally copy .env.example to .env and edit it. Preserve existing local configuration when updating a service. Environment variables override the file; .env is ignored by Git and excluded from Docker builds.

Variable Purpose
APP_NAME API title; defaults to FastAPI Service.
APP_VERSION Version exposed in the OpenAPI document; defaults to 0.1.0.
ENVIRONMENT development, test, or production; defaults to development.
ALLOWED_HOSTS Comma-separated hosts. Required and cannot contain * in production.
CORS_ORIGINS Optional comma-separated browser origins. Cannot use * with credentials.
CORS_METHODS Comma-separated browser methods; defaults to GET.
CORS_HEADERS Comma-separated browser request headers; defaults to Content-Type,X-Request-ID.
CORS_ALLOW_CREDENTIALS Enables browser credentials for explicit origins; defaults to false.
DOCS_ENABLED Controls /docs, /redoc, and /openapi.json; defaults off in production.
LOG_LEVEL DEBUG, INFO, WARNING, ERROR, or CRITICAL.
DATABASE_URL postgresql+psycopg URL required by database code and migrations.
DATABASE_REQUIRED Makes readiness verify PostgreSQL and requires DATABASE_URL at startup.
DATABASE_CONNECT_TIMEOUT_SECONDS PostgreSQL connection timeout; defaults to 10.
DATABASE_POOL_SIZE Persistent connection pool size; defaults to 5.
DATABASE_MAX_OVERFLOW Temporary connections above the pool size; defaults to 10.
DATABASE_POOL_TIMEOUT_SECONDS Time to wait for a pooled connection; defaults to 30.
DATABASE_POOL_RECYCLE_SECONDS Recreates connections before server-side idle limits; defaults to 1800.
DATABASE_POOL_PRE_PING Verifies a pooled connection before reuse; defaults to true.
DATABASE_STATEMENT_TIMEOUT_SECONDS Maximum database statement duration for application connections; defaults to 30.
DATABASE_LOCK_TIMEOUT_SECONDS Maximum wait for a database lock; defaults to 10.
DATABASE_IDLE_TRANSACTION_TIMEOUT_SECONDS Maximum idle time inside a transaction; defaults to 60.

Use only postgresql+psycopg://USER:PASSWORD@HOST:PORT/DATABASE; other PostgreSQL URL schemes are rejected during startup configuration. URL-encode special characters in credentials. Never commit real credentials.

PostgreSQL and migrations

Provision a PostgreSQL database and set DATABASE_URL. Shared Docker Compose orchestration belongs in the consuming project's infrastructure repository; this template supplies its own Dockerfile.

src/core/database.py provides the declarative Base, app-scoped async engine and session factory, and get_session FastAPI dependency. Sessions close after requests. Mutating repositories or services must explicitly commit their transactions. Application logs are JSON records that include a request ID, method, path, status, and duration for completed HTTP requests. Unexpected HTTP errors return the standard JSON error through CORS and request middleware; X-Request-ID is exposed to permitted browser origins. HTTP exception headers such as WWW-Authenticate, Allow, and Retry-After are preserved.

Exception logs retain the exception type and stack frame locations, but omit exception messages, SQL parameters, source text, and chained exception details. This avoids copying request values or PostgreSQL row diagnostics into logs. Do not put sensitive values in application log messages or URL paths. Errors after response headers have been sent abort the response with a generic error; the original exception is logged safely rather than passed to server logging.

Database connections set PostgreSQL statement, lock, and idle-transaction limits from the corresponding environment variables; tune them to the service's workload.

When CORS is enabled, declare only the browser methods and headers required by the service with CORS_METHODS and CORS_HEADERS. The defaults permit read requests with JSON request metadata only.

When adding the first model:

  1. Create the model under src/models/, inheriting from Base.
  2. Import it in alembic/env.py before target_metadata is assigned, so Alembic can see its table. Register later models there as well.
  3. Generate a migration and inspect its upgrade/downgrade operations:
uv run alembic revision --autogenerate -m "Create initial tables"
uv run ruff check alembic --fix
uv run ruff format alembic
uv run alembic upgrade head
uv run alembic check

There is no initial application migration. alembic upgrade head works against an empty database, but application tables appear only after you add models and migrations. Schema changes never run automatically at app startup. Run migrations as a separate deployment step.

Tests and Ruff

Without a database:

uv run pytest -m "not integration"
uv run ruff check .
uv run ruff format --check .
uv run pyright

For integration tests, provision a separate PostgreSQL database whose name ends in _test, and set TEST_DATABASE_URL in the process environment. Test-only settings do not belong in .env, which is validated as application configuration. For example, using disposable local test credentials:

docker run --name fastapi-service-test --rm -d -p 127.0.0.1:5433:5432 --tmpfs /var/lib/postgresql/data -e POSTGRES_USER=service -e POSTGRES_PASSWORD=service_test -e POSTGRES_DB=service_test postgres:17-alpine@sha256:f02121de6f74d30d8a94cd1d9584125e2178d7e6c377d8130112d4e52d867995
docker exec fastapi-service-test pg_isready -h 127.0.0.1 -U service -d service_test

Wait until pg_isready reports that PostgreSQL is accepting connections. Then run:

$env:TEST_DATABASE_URL = "postgresql+psycopg://service:service_test@127.0.0.1:5433/service_test"
uv run pytest
docker stop fastapi-service-test

Choose another free host port when necessary and update the test URL.

Integration tests check migrations and real SQLAlchemy sessions. They never fall back to DATABASE_URL. Missing TEST_DATABASE_URL skips integration tests; an invalid, unreachable or non-test database fails them.

GitHub Actions runs Ruff and the complete suite against a disposable PostgreSQL 17 service on every push and pull request. CI action revisions are pinned. uv 0.7.15 is pinned in CI and Docker; keep these versions aligned when updating uv. That uv version may download an older Python 3.13 patch locally or in CI; update the uv pin deliberately to refresh its Python download catalog.

Docker

docker build -t fastapi-service .
docker run --rm --name fastapi-service -p 127.0.0.1:8000:8000 fastapi-service

The image runs as UID 10001, listens on container port 8000, and has a Docker health check against /healthz. The probe always connects to 127.0.0.1:8000 inside the container and selects a permitted Host header from ALLOWED_HOSTS, so strict production host settings work without allowing arbitrary hosts. Wildcard subdomains use a matching healthcheck hostname; no external DNS lookup is made. CI verifies this with ENVIRONMENT=production and ALLOWED_HOSTS=api.example.com. Supply configuration with environment variables or --env-file .env when needed. A database on another container must be reached through its Docker network hostname; localhost inside the app container refers to the app itself.

Run migrations separately on the same network and with the same database configuration, overriding the image command with alembic upgrade head.

Structure

src/
  api/        # Versioned application routers and Pydantic HTTP schemas
  core/       # Settings, logging, middleware, database and shared dependencies
  domain/     # Domain entities, protocols and domain exceptions (add per service)
  repositories/ # Database implementations of domain protocols (add per service)
  routers/    # Operational routes, such as liveness and readiness probes
  services/   # Use-case orchestration (add per service)
  main.py
tests/        # Unit tests and optional PostgreSQL integration tests
alembic/      # Migration environment and version scripts
.github/
  copilot-instructions.md # Template-wide agent instructions
  instructions/ # Scoped architecture, API, configuration, test and migration rules
  workflows/  # Tests and Ruff

New domain APIs belong under src/api/v1/; keep handlers thin and call services. Services own use-case orchestration and depend on repository protocols; repositories own SQLAlchemy queries. Pydantic request and response models belong in src/api/, and SQLAlchemy models belong in src/models/. Each service owns its models, migrations, and database configuration.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages