# Add Health Check Endpoints to a FastAPI App

Yes. An agent keeps your FastAPI liveness route, adds a readiness route that runs a real query against Postgres, tests both with pytest, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/fastapi/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads what the app already answers before it adds a route, because many FastAPI projects have a health route that says less than it seems to. In a project shaped like fastapi/full-stack-fastapi-template the backend lives under `backend/`: `pyproject.toml` requires Python `>=3.14,<4.0`, `fastapi[standard]`, `sqlmodel`, `psycopg[binary]`, `alembic` and `sentry-sdk[fastapi]`, with `pytest`, `mypy` in strict mode, `ty`, `ruff` and `coverage` in the dev group and a `uv.lock`. `app/api/routes/utils.py` already declares `GET /health-check/` under the `/utils` prefix, and it returns the literal `True` without touching anything. `compose.yml` points the backend container's `healthcheck` at `/api/v1/utils/health-check/`, and `.github/workflows/test-docker-compose.yml` curls the same path after `docker compose up`, so that route is load-bearing and stays exactly as it is.

What is missing is a route that fails when Postgres is gone. `app/core/db.py` builds one `engine` with `create_engine(str(settings.DATABASE_URL), pool_pre_ping=True)`, and `app/api/deps.py` wraps it as `get_db`, which yields a `Session` and is exposed as `SessionDep`. The agent adds `GET /ready/` beside the existing route in `utils.py`: it takes `SessionDep`, runs `session.exec(text("SELECT 1"))`, and answers `200` with `{"status": "ok", "database": "ok"}`. When the query raises `OperationalError` the handler logs the exception and returns a `JSONResponse` with status `503` and `{"status": "unavailable", "database": "unavailable"}`, nothing about the host or the connection string in the body. Both routes stay outside `get_current_active_superuser`, unlike the `test-email` route in the same file, so a probe needs no token.

Tests follow `backend/tests/conftest.py`: the session-scoped `db` fixture calls `init_db`, and the module-scoped `client` fixture is a `TestClient(app)`. The new `tests/api/routes/test_utils.py` asserts that `/health-check/` still answers `True`, that `/ready/` answers `200` with `database` equal to `ok` against the real test database, and that `/ready/` answers `503` when `get_db` is swapped through `app.dependency_overrides` for a dependency that raises `OperationalError`. The override is removed in a `finally` block so later test modules see the real session. No new fixture file, no mock of the engine.

Before it pushes, the agent runs what the repository's own scripts run: `uv run bash scripts/lint.sh`, which is `mypy app`, `ty check app`, `ruff check app` and `ruff format app --check`, and `uv run bash scripts/test.sh`, which runs pytest under `coverage` and prints the report. Strict mypy means the handler's return type is declared as a union of the response model and `JSONResponse`, and ruff's `T201` rule means the failure is logged, not printed. It adds the two routes to `backend/README.md` and leaves `compose.yml` alone, noting in the pull request that a reviewer can point a readiness probe at `/api/v1/utils/ready/` once it is deployed.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add health check endpoints to this FastAPI backend and open a pull request. Read backend/pyproject.toml, backend/app/main.py, backend/app/api/main.py, backend/app/api/routes/utils.py, backend/app/api/deps.py, backend/app/core/db.py, backend/tests/conftest.py, backend/scripts/lint.sh, backend/scripts/test.sh, compose.yml and .github/workflows/test-backend.yml first. Keep the existing GET /utils/health-check/ route unchanged because compose.yml and CI depend on it. Add GET /utils/ready/ in the same router: it takes SessionDep, runs SELECT 1 through the session, and returns 200 with {\"status\": \"ok\", \"database\": \"ok\"}; on OperationalError it logs the exception and returns a 503 JSONResponse with {\"status\": \"unavailable\", \"database\": \"unavailable\"} and nothing else in the body. Neither route may require authentication. Add backend/tests/api/routes/test_utils.py using the existing client fixture: one test for health-check, one for ready against the test database, and one that overrides get_db with app.dependency_overrides so it raises OperationalError and asserts 503, restoring the override afterwards. Run uv run bash scripts/lint.sh and uv run bash scripts/test.sh, fix anything they report, paste their output in the pull request description, and document both routes in backend/README.md. Do not change compose.yml or any other route.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request with a new handler in `backend/app/api/routes/utils.py`, a new `backend/tests/api/routes/test_utils.py`, and a short section in `backend/README.md`. The description shows a `curl` of each route from the sandbox with its status and body, and the output of `scripts/lint.sh` and `scripts/test.sh` from the branch, including the coverage table that `coverage report` prints.

The repository's `test-backend.yml` workflow runs on the pull request: it starts `db` and `mailpit` with `docker compose up -d --wait`, migrates with `scripts/prestart.sh`, runs the suite and then `coverage report --fail-under=90`. Because the new file tests every branch of the new handler, the threshold is more likely to rise than to fall. The agent pushes one commit for the route and its tests and one for the documentation.

A reviewer checks that `/health-check/` still answers `True` for the compose healthcheck, that `/ready/` sits outside every auth dependency, that the `503` body gives nothing away, and that the `OperationalError` test restores `dependency_overrides`. Then they decide whether to point their orchestrator's readiness probe at the new route and leave liveness on the old one.

## Run it on every new FastAPI service

A platform team that wants every Python service to answer the same two routes starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each service's own `deps.py` and `db.py`, so a service on SQLModel gets a `SELECT 1` through its session and one with a different driver gets a check through whatever it already opens, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run it starts, with a `session_url` for the result, so a small handler can post the pull request links to the team channel as they land.

## Why run it on Rush?

The route itself is short; the care is in not breaking the one that already exists and in proving the failure path. On a laptop the `503` test is the one that gets skipped because making Postgres unreachable is awkward. In a Rush sandbox the agent writes it with a dependency override, runs it with the rest of the suite, and the output is kept in the transcript beside the `curl` of each route, so the pull request shows the unavailable path working, not only the ok one.

The result passes the repository's own gates, strict mypy, `ty`, ruff and the coverage threshold in CI, before a reviewer opens it, and the same request body works unchanged across every FastAPI service the team owns.

## Frequently asked questions

### Why not change the existing health-check route to query the database?

Because `compose.yml` and `test-docker-compose.yml` use it as a liveness signal, and liveness should not depend on Postgres. If it did, a database outage would make the container restart loop for no gain. Adding a second route keeps liveness cheap and gives readiness its own answer.

### Does the readiness route need a token?

No. It is declared without the `get_current_active_superuser` dependency that `POST /utils/test-email/` uses, so an orchestrator or a load balancer calls it with no `Authorization` header. The route lives under `settings.API_V1_STR` like every other route, so its full path is `/api/v1/utils/ready/`.

### How is the database failure tested without stopping Postgres?

With `app.dependency_overrides`, which FastAPI provides for exactly this. The test replaces `get_db` with a generator that raises `OperationalError`, calls `/ready/`, asserts `503`, and removes the override in a `finally` block so the other modules that share the `client` fixture keep the real session.

### Will it pass strict mypy and the ruff rules?

The agent runs `scripts/lint.sh` before pushing. The handler declares its return type, the failure goes through `logging` rather than `print` because ruff's `T201` rule forbids print statements, and the test file is typed the way `test_users.py` is, with `TestClient` and `dict[str, str]` annotations.

## More FastAPI jobs

- [Add OpenTelemetry Tracing to a FastAPI Service](https://getrush.ai/run/add-opentelemetry/fastapi/)
- [Add Cursor Pagination to a FastAPI Endpoint from a Linear Issue](https://getrush.ai/run/add-pagination/fastapi/)
- [Add Rate Limiting to a FastAPI API](https://getrush.ai/run/add-rate-limiting/fastapi/)

## The same job on other stacks

- [Add Health Checks to a Fastify App](https://getrush.ai/run/add-health-checks/fastify/)
- [Add Health Checks to a Fiber API](https://getrush.ai/run/add-health-checks/fiber/)
- [Add Health Checks to a Flask App](https://getrush.ai/run/add-health-checks/flask/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
