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
Section titled “1. Install the test dependencies”pip install pytest httpxFastAPI’s TestClient is built on httpx, so both are required. Add them to your development
requirements, not your production image.
2. Test an endpoint
Section titled “2. Test an endpoint”Given a small app:
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 itemTest it through HTTP, the way clients use it:
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 == 422Run with pytest.
3. Replace dependencies, not code
Section titled “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.
import pytestfrom 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.fixturedef 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
Section titled “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:
import pytestfrom httpx import ASGITransport, AsyncClient
from app.main import app
@pytest.fixturedef anyio_backend(): return "asyncio"
@pytest.mark.anyioasync 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 == 200The 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.
5. Run the suite on every pull request
Section titled “5. Run the suite on every pull request”A minimal GitHub Actions workflow:
name: testson: [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: pytestWith the repository connected to QualityMax, Gate 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
Section titled “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 for running and reading k6 results.
Related
Section titled “Related”- Run Playwright tests on every pull request with GitHub Actions for the browser side of a FastAPI-backed app.
- Code Review & Gates for the full pull-request pipeline.