Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

290 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

API Forge — a FastAPI template that's actually opinionated

PythonLicense: MITLintTypesTests

A production-shaped FastAPI template that ships the boring decisions already made. OIDC + BFF authentication, type-safe persistence, durable workflows, clean-architecture scaffolding, and your choice of deployment target — all behind one CLI.

copier copy --trust gh:piewared/api-forge my-service
cd my-service && uv sync
uv run api-forge-cli dev up # full stack in Docker, hot reload

Open http://localhost:8000/docs and you have a running, authenticated, type-checked API.


What you actually get

A scaffold that encodes good patterns. One CLI command produces a fully wired entity — domain model, persistence model, repository, request/response DTOs, application service with proper transaction boundaries, and an HTTP router that's auto-discovered at startup. No edits to app.py ever.

api-forge-cli entity add Order
# → entities/service/order/{entity, table, repository, schemas, service, router}.py# → endpoints live at /api/v1/orders/ — no wiring required

BFF authentication that's not boilerplate. OIDC Authorization Code + PKCE with server-side sessions, HttpOnly signed cookies, CSRF protection, client fingerprinting, and JWKS-based token validation. Pre-seeded Keycloak in dev, managed IdP (Google / Microsoft / Okta / Auth0 / Cognito) in prod via config. The hard parts have already been gotten wrong by someone else.

Durable workflows when you need them. Temporal scaffolding with typed input/result, auto-discovered workflow + activity registry, and the canonical "endpoint → service → workflow start" pattern wired in one command:

api-forge-cli entity add Order --with-workflow OrderDispatch
# → also generates the workflow module and adds an async dispatch()# method to OrderService that starts it with idempotent IDs

Pick your deployment target. Docker Compose for prod, Kubernetes via Helm, or Fly.io. Each is an opt-in toggle at template-generation time — if you don't need k8s, the Helm machinery never lands in your repo.

Dev/prod parity by default. The dev stack is the prod stack: same PostgreSQL, same Redis, same Temporal, same Keycloak (dev only) — all in Docker Compose, started with one command.


Quick start

1. Generate a project

uv tool install copier # or: pip install -U copier
copier copy --trust gh:piewared/api-forge my-service
cd my-service

Copier asks a handful of questions. The defaults give you a slim project (no fly, no k8s); opt in to deployment targets you actually use:

QuestionDefaultWhat it controls
use_redisyesRedis caching, sessions, rate limiting
use_temporalyesTemporal workflow scaffolding + worker
use_postgresnoPostgres deps + URL (default is SQLite for fast start)
include_fly_deploynoapi-forge-cli fly command + Fly.io infra adapter
include_k8s_deploynoapi-forge-cli k8s command + Helm deployer + manifests

Toggling these off doesn't comment-out code — entire subtrees are excluded from the generated project. You only carry what you use.

⚠️ Copier needs --trust for templates with post-generation hooks. The hooks are open source — see copier.yml and scripts/post_gen_setup.py.

2. Install + run

uv sync
cp .env.example .env
uv run api-forge-cli dev up

The dev stack pulls and runs PostgreSQL, Redis, Temporal, Keycloak, and the API itself in Docker. First run takes a minute or two; subsequent starts are seconds.

Once healthy:

WhatURL
APIhttp://localhost:8000
Interactive docshttp://localhost:8000/docs
Keycloak (dev only)http://localhost:8080 (admin / admin)
Temporal UIhttp://localhost:8082

3. Iterate

api-forge-cli dev logs api # tail just the API
api-forge-cli dev restart api # restart after dependency changes
api-forge-cli dev down # stop everything

4. Update later

api-forge-cli update # pull template improvements; merges with your changes

Use api-forge-cli update rather than copier update directly. The template renames src/<package_name>/ after generation, which Copier doesn't know about; the wrapper handles the rename dance so Copier's three-way merge sees a tree shaped the way it expects, then restores the package layout afterwards. Net effect: template changes land as staged-but-uncommitted edits ready for git diff --staged and your usual review.


CLI tour

Everything lives under api-forge-cli. Subcommands group by concern:

api-forge-cli --help
dev Development environment commands
prod Production Docker Compose commands
k8s Kubernetes Helm deployment commands (toggle: include_k8s_deploy)
fly Fly.io deployment commands (toggle: include_fly_deploy)
config Configuration validation
entity Entity scaffolding (add / rm / ls)
workflow Temporal workflow scaffolding (when use_temporal=true)
activity Temporal activity scaffolding (when use_temporal=true)
secrets Secret generation and management
users Keycloak user management (dev)

Scaffolding

# CRUD entity — entity / table / repo / schemas / service / router + tests
api-forge-cli entity add Product
# Entity + Temporal workflow, fully wired:# - service.py auto-imports TemporalClientService and stores it# - router.py injects the temporal dep via FastAPI# - service.dispatch(<id>) starts the workflow with an idempotent ID
api-forge-cli entity add Order --with-workflow OrderDispatch
# Standalone workflow / activity — when the work spans multiple entities,# is scheduled, or isn't tied to a specific entity's lifecycle. Pick an# orchestrator entity and wire dispatch() there manually.
api-forge-cli workflow add OrderFulfillment # spans Order + Inventory + Shipment
api-forge-cli activity add send_welcome_email

Iteration

api-forge-cli dev up # local Docker Compose, hot reload
api-forge-cli fly sync # push current code to Fly main app (fast path)
api-forge-cli fly up # full Fly stack (services + main app)
api-forge-cli k8s up # deploy via Helm

fly sync is the tight code-iteration loop: skips the supporting-services phase and pre-flight, just builds and ships the main app image. fly up is the full reconcile (Redis + Temporal + Postgres + main app).


Architecture, briefly

HTTP request
│
▼ router.py — thin handler: delegates to service
▼ service.py — owns transactions; raises domain errors
▼ repository.py — CRUD against the table
▼ table.py — SQLModel persistence
▼ entity.py — Pydantic domain model with invariants

Services own commit/rollback. Routers translate domain errors to HTTP status codes. Entities never import SQLModel (persistence stays at the edge). Each new entity follows this shape because the scaffold encodes it. Deep dive →

For background work, two layers of choice:

NeedUse
Durable, retryable, replayableTemporal (scaffolded)
Fire-and-forget after the responseFastAPI BackgroundTasks

The architecture doc explains the asymmetry and shows the canonical patterns for both.


Authentication

OIDC Authorization Code + PKCE with server-side sessions:

  • All web auth endpoints under /auth/web (login, callback, me, refresh, logout).
  • HttpOnly + signed session cookies; CSRF token rotated on refresh.
  • redirect_uri is server-configured — never trusted from the client.
  • Client fingerprinting binds sessions to the user agent.
  • JWKS-based JWT validation for non-cookie clients (mobile, service-to- service).

Dev: pre-seeded Keycloak realm. Prod: configure any managed IdP (Azure AD, Okta, Auth0, Google, Cognito) by setting oidc.providers in config.yaml.

Auth deep dive → · Sessions & cookies →


Configuration

config.yaml is the single source of truth, with environment variable substitution everywhere:

database:
url: "${DATABASE_URL:-sqlite:///./database.db}"redis:
enabled: trueurl: "${REDIS_URL:-redis://localhost:6379}"temporal:
enabled: trueurl: "${TEMPORAL_URL:-temporal:7233}"oidc:
providers:
google:
issuer: "${OIDC_GOOGLE_ISSUER:-https://accounts.google.com}"client_id: "${OIDC_GOOGLE_CLIENT_ID}"client_secret: "${OIDC_GOOGLE_CLIENT_SECRET}"

.env provides per-environment values. Pydantic models enforce the shape at startup. Service feature flags (redis.enabled, temporal.enabled) are honoured at runtime — disable Temporal and the workflow scaffolds refuse to run, the worker exits cleanly, and rate-limiting falls back to in-memory.

Configuration reference →


Testing

uv run pytest # everything
uv run pytest tests/unit/ # unit only — fast, no infra
uv run pytest tests/integration/ # needs dev stack running
uv run pytest tests/e2e/ # full auth + workflow paths

Testing strategy →


Deployment

Three first-class targets, each opt-in via copier:

TargetCommandWhen
Docker Composeapi-forge-cli prod upSingle host, simple ops
Kubernetesapi-forge-cli k8s upMulti-node, autoscaling, your cluster
Fly.ioapi-forge-cli fly upManaged multi-region, no ops

For Fly, fly sync is the dev loop — fast iteration on the main app without touching supporting services.


Project structure

my-service/
├── my_service/ # Your application package
│ ├── app/
│ │ ├── api/http/ # FastAPI factory, middleware, routers
│ │ │ ├── app.py # Slim create_app() factory
│ │ │ ├── lifespan.py # Startup/shutdown sequencing
│ │ │ ├── deps.py # Cross-cutting FastAPI dependencies
│ │ │ └── routers/ # Auth + auto-discovery loader
│ │ ├── core/services/ # Cross-cutting infra (JWT, OIDC, Redis, …)
│ │ ├── entities/ # Domain entities (CLI scaffolds here)
│ │ │ ├── core/ # Auth-essential (User, UserIdentity)
│ │ │ └── service/ # Generated CRUD entities
│ │ │ └── <name>/{entity, table, repository, schemas, service, router}.py
│ │ ├── runtime/ # Config loading, DB init
│ │ └── worker/ # Temporal workflows + activities
│ └── cli/ # api-forge-cli commands
├── tests/ # Unit, integration, e2e
├── docs/ # Architecture, auth, deployment guides
├── docker-compose.dev.yml # Dev stack
├── docker-compose.prod.yml # Prod-shaped Compose stack
├── config.yaml # Single-source config with env substitution
└── pyproject.toml

Who this is for

A good fit if:

  • You're building a backend serving web/SPA clients and want OIDC sessions done correctly instead of rolling your own.
  • You want production-shaped local dev — same Postgres, same Redis, same Temporal — without a full afternoon of setup.
  • You want a scaffold that encodes architectural decisions, so a feature is one CLI command instead of seven files of boilerplate.

Probably not a fit if:

  • You want a minimal "hello world" REST API with zero infra.
  • You don't want Docker in your workflow.
  • You're committed to a stack the template doesn't speak (Django, Flask + SQL Alchemy classic, etc.).

Documentation


Requirements

  • Python 3.13+
  • Docker & Docker Compose
  • uv (recommended) or pip + virtualenv
  • Helm v3 + kubectl if generating with include_k8s_deploy=yes
  • fly CLI if generating with include_fly_deploy=yes

License & support

MIT — see LICENSE.

Bugs and feature requests via GitHub Issues. Questions and ideas via Discussions.

About

A production-ready FastAPI template for building scalable Python APIs with PostgreSQL, SQLModel, Redis, and Temporal—fully configured for local and cloud deployment.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages