Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 50 ยท Projects

Project: Production-ready service

Build a small FastAPI service with an app factory, settings, a database, one error shape, request-id middleware, a health endpoint, tests and a Dockerfile.

The earlier projects were about features. This one is about everything around the features: the parts that decide whether a service can be run, debugged and changed at 3 a.m. You will build a tiny notes service, but the interesting code is the frame around it: an app factory, settings, a database dependency, one error shape for every failure, a request-id middleware, a health endpoint, tests and a Dockerfile.

Each piece has its own lesson earlier in the course, so this page shows how they fit together. Follow the links if a detail feels new. On the site everything runs in a single file; the layout section shows how you would split it across modules on your machine.

The plan

Eight pieces of a real service

App factory One function builds the app.
Settings Config comes from outside.
Database One session per request.
One error shape Clients parse one format.
1 / 2

The key design decision is the factory. Instead of creating app = FastAPI() at import time and reading global settings, you write create_app(settings). Tests call it with test settings and an in-memory database; production calls it with real ones. Nothing is shared between two apps, so tests cannot leak into each other. See Settings and configuration for the settings idea and Testing FastAPI apps for isolation.

Layout on your machine

A service of this size usually looks like this. Each file has one job:

TEXT
notes-service/
  app/
    main.py          # create_app() and the module-level `app`
    settings.py      # Settings class (pydantic-settings)
    database.py      # engine/connection and get_db dependency
    errors.py        # AppError and the exception handlers
    middleware.py    # request-id middleware
    routers/
      notes.py       # APIRouter with the note endpoints
      health.py      # /health
    schemas.py       # Pydantic models
  tests/
    conftest.py      # client fixture with a fresh database
    test_notes.py
  Dockerfile
  pyproject.toml

Routers and project layout explains the split. The live code below puts the same pieces in one file, in the same order.

The service

Read the code in four blocks: settings and schemas, errors, the factory with middleware, and the endpoints. The settings here are a plain Pydantic model; in a real project you would use pydantic-settings so values come from environment variables (shown later).

Python A notes service built by an app factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four things to notice in the output:

  • Every failure has the same shape: {"error": {"code", "message", "request_id", ...}}. A client needs one parser, not one per status code. Missing routes and HTTPException go through the Starlette handler, validation errors get a friendly fields list, and your own AppError carries a machine-readable code.
  • The request_id in an error body matches the X-Request-ID response header. When a user reports a problem, they give you that one value and you search the logs for it. The middleware accepts an id from the caller (so a gateway can pass its own) and invents one otherwise.
  • The 409 for the third note comes from a business rule, not from validation. AppError keeps such rules out of the HTTP vocabulary until the last moment.
  • /health touches the database, so it fails when the database is unreachable. See Middleware and CORS for how call_next works and Status codes and error handling for handlers.

Unexpected exceptions (a real bug) are handled by Starlette's outermost layer, which sits outside your middleware, so a 500 response will not carry your X-Request-ID. In production, log the request id at the start of the middleware, with the request, so it is in the logs even when the response is a bare 500.

Settings from the environment

On your machine the settings class reads environment variables, so the same image runs in development and production with different values. Read-only, because the browser has no real environment:

Python
# app/settings.py
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="NOTES_", env_file=".env")

    environment: str = "development"
    max_notes: int = 1000
    database_url: str = "notes.db"

@lru_cache
def get_settings() -> Settings:
    return Settings()

# main.py
app = create_app(get_settings())

With the prefix, NOTES_MAX_NOTES=50 overrides max_notes. Secrets such as a database password come only from the environment (or a secret manager), never from the repository.

Testing the service

Because of the factory, each test builds its own app and its own in-memory database. The test below repeats the factory in a shortened form (the same routes and handlers) so that it stays runnable on its own, and then checks the behaviours that matter: success, the error shape, the request id and the business rule.

Python Tests with a fresh app per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real project the same functions live in tests/, and a client fixture builds TestClient(create_app(Settings(database_url=":memory:"))). Run them with pytest -q in your CI pipeline, before every build of the image.

The Dockerfile

The last piece is the image. It is read-only here; Deployment explains each choice and the Docker tutorial goes much deeper.

DOCKERFILE
FROM python:3.14-slim

ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /srv

# Install dependencies first so this layer is cached until they change
COPY pyproject.toml ./
RUN pip install --no-cache-dir .

COPY app ./app

# Do not run as root
RUN useradd --create-home appuser
USER appuser

EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

The HEALTHCHECK calls the /health endpoint you wrote, so the platform can restart a container that is up but broken. Settings arrive through docker run -e NOTES_DATABASE_URL=..., and the exec-form CMD lets uvicorn receive the stop signal and shut down gracefully.

Checklist before you ship

  • Config only from the environment; no secrets in code or image.
  • One error shape, and the request id in both the response header and your logs.
  • A health endpoint that checks the dependencies you cannot live without.
  • Tests that build a fresh app, run in CI before the image is built.
  • A non-root container with a health check and an exec-form CMD.
  • Migrations for schema changes (Migrations with Alembic) instead of CREATE TABLE at startup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why build the app with a create_app(settings) factory?

    A factory takes its configuration as an argument, so tests can build isolated apps and production can build a real one.
  2. 2. What is the benefit of putting the request id in both the response header and the error body?

    The id ties a client-visible failure to server-side logs, which is the first step of debugging in production.
  3. 3. What should a health endpoint do in a production service?

    A useful health check proves the service can really do its job, and it must never expose secrets.
  4. 4. Why does the Dockerfile copy pyproject.toml and install dependencies before copying the app code?

    Docker caches layers in order. Code changes often and dependencies rarely, so installing them first saves rebuild time.

Summary

  • A create_app(settings) factory gives every test and environment its own isolated app.
  • Settings come from the environment (pydantic-settings in a real project); secrets never live in the repository.
  • Register handlers so every failure returns one error shape with a machine-readable code and the request id.
  • A request-id middleware accepts or generates an id and adds it to every response.
  • /health checks real dependencies; the Dockerfile uses it in a HEALTHCHECK.
  • Tests build a fresh app and run in CI; the image runs as a non-root user with an exec-form CMD.

Now sharpen your skills with the Exercises with solutions.