> Full documentation index: [llms.txt](https://docs.qualitymax.io/llms.txt)

# Test a FastAPI app with pytest

This guide sets up pytest for a FastAPI service, replaces real dependencies in tests, covers async
endpoints, and gets the suite running on every pull request. It ends with load testing generated from
the schema FastAPI already publishes.

## 1. Install the test dependencies

```bash
pip install pytest httpx
```

FastAPI's `TestClient` is built on `httpx`, so both are required. Add them to your development
requirements, not your production image.

## 2. Test an endpoint

Given a small app:

```python
# app/main.py
from fastapi import Depends, FastAPI, HTTPException

app = FastAPI()


class ItemStore:
    def get(self, item_id: int) -> dict | None:
        raise NotImplementedError("connect a real database here")


def get_store() -> ItemStore:
    return ItemStore()


@app.get("/health")
def health() -> dict:
    return {"status": "ok"}


@app.get("/items/{item_id}")
def read_item(item_id: int, store: ItemStore = Depends(get_store)) -> dict:
    item = store.get(item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item
```

Test it through HTTP, the way clients use it:

```python
# tests/test_health.py
from fastapi.testclient import TestClient

from app.main import app

client = TestClient(app)


def test_health_reports_ok():
    response = client.get("/health")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}


def test_item_id_must_be_an_integer():
    response = client.get("/items/not-a-number")
    assert response.status_code == 422
```

Run with `pytest`.

## 3. Replace dependencies, not code

`app.dependency_overrides` swaps a dependency for the duration of a test, so the endpoint, its
validation, and its error handling all still run. Clear overrides after each test so they never leak
between tests.

```python
# tests/test_items.py
import pytest
from fastapi.testclient import TestClient

from app.main import app, get_store


class FakeStore:
    def __init__(self, items: dict[int, dict]):
        self.items = items

    def get(self, item_id: int) -> dict | None:
        return self.items.get(item_id)


@pytest.fixture
def client():
    app.dependency_overrides[get_store] = lambda: FakeStore({1: {"id": 1, "name": "Widget"}})
    yield TestClient(app)
    app.dependency_overrides.clear()


def test_returns_existing_item(client):
    response = client.get("/items/1")
    assert response.status_code == 200
    assert response.json() == {"id": 1, "name": "Widget"}


def test_missing_item_is_404(client):
    response = client.get("/items/999")
    assert response.status_code == 404
    assert response.json() == {"detail": "Item not found"}
```

Assert on the status code and the body. A test that only checks `status_code == 200` passes for an
endpoint that returns the wrong data.

## 4. Test async code

`TestClient` handles `async def` endpoints already. When the test itself needs to `await` something,
such as an async database fixture, use `httpx.AsyncClient` with the ASGI transport:

```python
# tests/test_async.py
import pytest
from httpx import ASGITransport, AsyncClient

from app.main import app


@pytest.fixture
def anyio_backend():
    return "asyncio"


@pytest.mark.anyio
async def test_health_async():
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        response = await ac.get("/health")
    assert response.status_code == 200
```

The `anyio` marker comes from the AnyIO pytest plugin, which is installed with FastAPI. The
`anyio_backend` fixture pins these tests to asyncio. Without it, AnyIO 4.12 and later run each test
on every installed backend, and earlier releases also try Trio, which fails when Trio is not
installed. See [AnyIO backend
selection](https://anyio.readthedocs.io/en/stable/testing.html#specifying-the-backends-to-run-on).

## 5. Run the suite on every pull request

A minimal GitHub Actions workflow:

```yaml
# .github/workflows/tests.yml
name: tests
on: [pull_request]

jobs:
  pytest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
          cache: pip
      - run: pip install -r requirements.txt pytest httpx
      - run: pytest
```

With the repository connected to QualityMax, [Gate Gamma](/code-review-gates-gamma/) also runs
`pytest` on each pull request in an isolated cloud sandbox and reports a failing gate when tests
fail. That sandbox receives none of your secrets and has a time limit, so keep the default suite
self-contained: fakes through dependency overrides, no live databases or third-party APIs. Mark the
tests that need real infrastructure and run them in a separate job.

## 6. Load-test from the OpenAPI schema

FastAPI serves its OpenAPI schema at `/openapi.json`. Where performance testing is available on your
plan, open **Performance** in QualityMax, choose **Generate from API Spec**, and provide that
schema's URL or paste its contents to generate a k6 script for the endpoints. Review the generated
thresholds and request mix, and point it at a test environment, never production. See
[Performance](/performance/) for running and reading k6 results.

## Related

- [Run Playwright tests on every pull request with GitHub Actions](/guides/playwright-tests-github-actions/)
  for the browser side of a FastAPI-backed app.
- [Code Review & Gates](/code-review-gates/) for the full pull-request pipeline.
