Skip to content

The fastapi-service template

A FastAPI web service where the business rules live in a pure domain, the database and other services behind repositories and clients, each operation in a service, and HTTP only in the API layer. FastAPI itself imposes no structure; this template brings one and checks it.

archvow init orders_api -t fastapi-service -a architects=@my-team

It shares with pyspark-pipeline everything that is not about the stack - the init answers (language, platform, CI, AI assistants, Sonar, internal sources), the Git hook, the code owners, the CI files - through a common base, python-base. The questions, the safety analysis and the their tests work the same way.

init answers

All the answers of the pyspark-pipeline template except the Spark ones (spark_version, scheduler), plus:

Answer Default Meaning
fastapi_version 0.143 the FastAPI line the project pins; archvow doctor checks the installed one
python_version 3.12 minimum Python: 3.11 to 3.13

A database is approved like any package: -a dependencies=sqlalchemy (written into pyproject.toml and requirements.txt by its pip name).

Layers

Layer Holds May import Never
p0_common settings, the database session, the dependencies routes ask for (current user...) - business rules
p1_domain Pydantic models, domain errors, pure business rules p0_common database, files, network, FastAPI
p2_io repositories and clients of other services p0_common, p1_domain business rules, HTTP routes
p3_services one business operation each; owns the transaction p0_common, p1_domain, p2_io HTTP (requests, status codes, HTTPException)
p4_api routers and the app p0_common, p1_domain, p3_services the database or another service directly, business rules

A router never reaches a repository: p4_api may not import p2_io, so every route goes through a service (ARCH005).

Component types

Type File Public API Test Questions
model p1_domain/<name>_model.py class <Name> (Pydantic) unit 3: required fields, valid values, fields that never leave the service
error p1_domain/<name>_error.py class <Name>Error unit 2: the HTTP status, what the message must never say
logic p1_domain/<name>.py (verb_noun) <name>(...) unit 3: the rule, invalid input, rounding
utility p0_common/<name>.py (verb_noun) <name>(...) unit 2: what it takes and returns, invalid input
dependency p0_common/get_<name>.py get_<name>(...) unit 2: what it provides, what happens when it cannot
repository p2_io/<name>_repository.py class <Name>Repository integration 4: not found, transactions, concurrent updates, big queries
client p2_io/<name>_client.py class <Name>Client integration 3: timeout, retries, the other service down
service p3_services/<name>.py (verb_noun) <name>(...) integration 5: the steps, missing data, repeated calls, who may, all or nothing
router p4_api/<name>_router.py router: APIRouter and its routes integration 5: who may call, statuses, validation errors, lists, retried POST
app p4_api/<name>.py create_app() -> FastAPI integration 4: routers and prefix, error mapping, lifespan, CORS

Business examples (archvow example add, Concepts) go on router (input/request.json - method, path, body, and a seed file when the route needs existing data - and expected/response.json - status and body; run with the integration tests through the TestClient: the default home of a ticket's examples), logic and utility. Not on service, repository or client: their tests use fakes, and the router's example covers them from the outside.

init creates two foundations, settings (Settings, get_settings(), read from the environment) and logging_setup (setup_logging(), called once by the app: the only place that configures logging, ARCH059; every module logs through logging.getLogger(__name__)). A project made with an earlier version gets logging_setup with archvow init <package> --force. The parameters of a utility, logic, dependency or service function are the implementer's, unless the spec fixes them with --signature.

Routes

A route is a public promise and an attack surface, so it is declared like a public function:

archvow component add router orders -d "The order API" -u create_order,get_order \
    -r "post_order: POST /orders" -r "read_order: GET /orders/{order_id}"
archvow component edit orders_router -r "post_order: POST /orders" -r "read_order: GET /orders/{order_id}" \
    -r "list_orders: GET /orders"                     # the complete new list

In the code each route is a function of that name, decorated with that method and path:

@router.get("/orders/{order_id}")
def read_order(order_id: int, customer: _Customer) -> Order:
    """One order of the calling customer."""
    return get_order(customer, order_id)

A route in the code that the spec does not declare - even on a private function - fails (ARCH002), and so does another method or path (ARCH004). A declared route not written yet is planned until the release gate (check --complete).

Rules

On top of archvow's generic rules (ARCH*, STY*), the template switches on:

Code Fails when
FAPI001 a known blocking call (requests.*, httpx.get..., time.sleep, subprocess.run, urlopen, open()) directly inside async def
FAPI002 HTTPException outside p4_api and the p0_common dependencies
FAPI003 FastAPI() created outside the app component
FAPI004 an on_event startup or shutdown handler instead of the app's lifespan
FAPI005 (warning) a route that declares no response (response_model= or a return type)

Ruff adds its own FastAPI rules (FAST: Annotated dependencies, path parameters, redundant response models) and ASYNC, plus PEP 8, docstrings, annotations and the security rules (S). See Rules.

What must never happen

The guide words are those of a web service: concurrent replaces less.

Guide word Typical hazard Example invariant Tested by (--verify for the expert checks)
exposed a customer reads another customer's order "a customer only ever reads their own orders" property_test: Hypothesis generates two customers
repeated a retried POST takes the payment twice "one idempotency key captures at most one payment" runtime: a guard in the service, marked # archvow: enforces[...], backed by a unique constraint in the database
concurrent two requests update the same stock "stock is never negative" runtime (a guard in the service, backed by a CHECK constraint), or model_check: a TLA+ model of the protocol
partial the order is saved, the payment is not "an order is paid or cancelled, never stuck in between (saved but unpaid)" model_check (TLA+), plus a test of the failure path
wrong an illegal state change "an order only moves along the allowed transitions" proof: the transition function proven in Dafny; the Python function in p1_domain is checked against it by a property test
more an unbounded list "no response returns more than 100 rows" property_test

archvow checks that the test (or the expert check) exists and is of the right kind; the model checker and the proof tool run in your CI. Nothing proves the FastAPI wiring itself: the few properties that matter are proven where they live - the pure domain, the database constraints, the protocol model - and the routes are covered by contract and property tests.

Tests

  • Unit (models, errors, rules, dependencies): plain objects, fast.
  • Integration (repositories, clients, services, routers, the app): FastAPI's TestClient with the app of the app component, a database in a temporary file, httpx.MockTransport for other services; @pytest.mark.integration.

Running

make run                       # uvicorn --factory --reload --ws none, the app of the `main` component
make test                      # every test, with coverage

Settings come from the environment (get_settings(), pydantic-settings); .env is gitignored. With a database: a dependency provides the session, repositories use it, services own the transaction, and the schema changes only through migrations in migrations/ (Alembic, which may import sqlalchemy and alembic there).

Following FastAPI

FastAPI moves fast; archvow follows it on purpose, never automatically:

  1. Pinned: the project pins fastapi_version (in pyproject.toml and the development requirements); archvow doctor warns when the installed version differs. An upgrade is a merge request, judged by the checks and the tests.
  2. Ruff's FastAPI rules follow FastAPI's own recommendations with each ruff release.
  3. An early-warning job in archvow's own CI (fastapi-canary, from a weekly pipeline schedule) runs the reference service against the newest FastAPI and Pydantic. When FastAPI changes a convention, the template is updated in a new archvow version.
  4. Projects adopt it deliberately: archvow init <package> --force, review, commit (upgrading).

What init writes

Like the pyspark-pipeline template, without entrypoint.sh, dags/ or oozie/: README.md, AGENTS.md and the assistants' files, pyproject.toml (FastAPI, pydantic-settings, uvicorn, and the test settings), requirements.txt, Makefile (make run), ruff.toml (with FAST and ASYNC), the Git hook, the code owners, the CI, .gitignore (with .env) and .archvow/.

A finished service:

src/orders_api/
├── p0_common/    settings.py  logging_setup.py  get_current_user.py
├── p1_domain/    order_model.py  new_order_model.py  order_not_found_error.py
├── p2_io/        orders_repository.py
├── p3_services/  create_order.py  get_order.py
└── p4_api/       orders_router.py  main.py
tests/            one test per component, mirroring src/, and integration/

The generated README.md walks through this example from the empty project to a running service, with every command.

The finished example

The archvow repository holds this service finished, its spec and its code: examples/fastapi-service (English documents). Every file was written as the generated README says - archvow commands for the spec, then the code from the specs - and the checks pass: archvow check --complete, ruff and the tests, including the two invariants (orders_router.INV1, a customer never reads another customer's order; create_order.INV1, every saved order has an amount greater than zero), both proven by Hypothesis property tests.

cd examples/fastapi-service
python3 -m pip install -r requirements.txt
archvow check --complete && make test
make run                                     # then, in another terminal:
curl -X POST localhost:8000/v1/orders -H "X-Customer: ann" -H "Content-Type: application/json" -d '{"amount": "5.00"}'
curl localhost:8000/v1/orders/1 -H "X-Customer: ann"    # 200; with X-Customer: bob, 404

Open http://localhost:8000/docs for the OpenAPI page FastAPI generates. To see a check fail, add a route to orders_router.py without declaring it, or import orders_repository from the router, and run archvow check. Behind a company proxy, add --noproxy localhost to curl. The PySpark template's example is in examples/pyspark-pipeline/.