fastapi-app

A FastAPI web-application guide based on hexagonal architecture, which keeps business logic separate from web and database code.

In plain words
What is it for?
It helps structure FastAPI projects with application factories, dependency injection, Jinja2 templates, Bootstrap styling, and htmx interactions.
Why use it?
This separation makes the application easier to test with fake components and to run with real production components.

Command

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/romilly/claude-code-helpers/fastapi-app
Clone the repo
git clone --depth 1 https://github.com/romilly/claude-code-helpers
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 1,365 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01365
Opus 5 $0.00000 $0.00682
Sonnet 5 $0.00000 $0.00273
Haiku 4.5 $0.00000 $0.00136

Measured yesterday against content hash 3f4273275bf5, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

fastapi-app scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

resources/commands/fastapi-app.md · 219 lines

How it starts

The opening of the file, as written. The whole thing — 219 lines — stays where its author put it; the contents beside it link to each section on GitHub.

FastAPI Web Application Guide

Architecture

Use hexagonal architecture (ports and adapters):

src/project_name/
├── domain/           # Pure business logic, no I/O
├── ports/            # Abstract interfaces (ABCs)
├── adapters/         # Implementations
│   ├── web_app.py    # FastAPI app factory
│   └── *_repository.py
└── templates/        # Jinja2 templates

App Factory Pattern

Create the FastAPI app via a factory function with dependency injection:

from fastapi import FastAPI
from project.ports.some_port import SomePort

def create_app(dependency: SomePort) -> FastAPI:
    app = FastAPI()
    # Define routes that use the injected dependency
    return app

This enables testing with fake adapters and production with real adapters.

Frontend Stack

  • Bootstrap 5 via CDN for styling
  • htmx via CDN for dynamic interactions
  • Jinja2 templates in src/project_name/templates/

Base template includes:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://unpkg.com/[email protected]"></script>

Dependencies

In requirements.txt:

fastapi
uvicorn
jinja2

In requirements-test.txt:

httpx
playwright
pytest-playwright

Install Playwright browser: playwright install chromium

Testing Strategy

1. Endpoint Tests (TestClient)

Use FastAPI's TestClient with fake adapters:

from fastapi.testclient import TestClient
from project.adapters.fake_adapter import FakeAdapter
from project.adapters.web_app import create_app

@pytest.fixture
def client() -> TestClient:
    adapter = FakeAdapter()
    adapter.add(sample_data)
    app = create_app(adapter)
    return TestClient(app)

def test_endpoint(client: TestClient) -> None:
    response = client.get("/")
    assert response.status_code == 200

2. E2E Tests (Playwright)

Use a test server utility with dynamic port allocation:

# tests/helpers/test_server.py
import socket
import threading
from contextlib import contextmanager
from typing import Generator

import httpx
import uvicorn
from fastapi import FastAPI


def find_free_port() -> int:
    """Find an available port by letting the OS assign one."""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def wait_for_server(url: str, timeout: float = 5.0) -> bool:
    """Wait for server to be ready."""
    import time
    start = time.time()
    while time.time() - start < timeout:
        try:
            response = httpx.get(url, timeout=0.5)
            if response.status_code == 200:
                return True
        except httpx.RequestError:
            pass
        time.sleep(0.1)
    return False


@contextmanager
def run_test_server(app: FastAPI) -> Generator[str, None, None]:
    """Context manager to run a test server, yields the base URL."""
    port = find_free_port()
    config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")
    server = uvicorn.Server(config)

    thread = threading.Thread(target=server.run, daemon=True)
    thread.start()

    url = f"http://127.0.0.1:{port}"
    if not wait_for_server(url):
        raise RuntimeError(f"Server failed to start on {url}")

    try:
        yield url
    finally:
        server.should_exit = True
        thread.join(timeout=2)

Read the full file on GitHub · 219 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 219 lines · 0 tokens per session scan A 3f4273275bf5

Subscribe to this mod's changes

fastapi-app is a command published in the GitHub repository romilly/claude-code-helpers (2 stars, last pushed 6mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,365 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.