Skip to main content

APIs · Intermediate · 22 min

Test an API automatically with pytest and Schemathesis

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · pytest 9.2 · httpx 0.28 · Schemathesis 4.33 · FastAPI 0.165

You will write black-box pytest tests for a running API with httpx, let Schemathesis generate thousands of requests from its OpenAPI document to find a server error and a response that breaks the schema, fix both, and finish with one script that runs the whole contract check in CI.

On this page

Hand-written API tests check the cases you thought of. They are worth having, and they are also exactly as wide as your imagination. The bugs that reach production are usually in the cases nobody thought of: a page size of zero, a field that comes back as the wrong type on one route, a body that is not valid UTF-8.

Schemathesis fills that gap. It reads your API's OpenAPI document, works out what every operation accepts and promises to return, then generates requests: boundary values, odd strings, missing fields and plain random data. It sends them to the running API and checks each response against the document. A crash, an undocumented status code or a body that does not match its schema fails the run, along with a curl command that reproduces it.

In this tutorial you test a small product-catalogue API in two layers. First, pytest and httpx check the main flows from the outside, the way a client would. Those tests pass. Then Schemathesis finds two bugs they missed. You fix both, add regression tests, and wrap everything in one script your CI runs on every push.

Both layers are black-box: they only speak HTTP to a URL. The API here is FastAPI because it writes its OpenAPI document for you, but the tests work unchanged against an API written in Go, Node.js, PHP or anything else that publishes an OpenAPI document. For the in-process style that only works with FastAPI, see test a FastAPI app with pytest and dependency overrides.

Step 1 · Create the project and the API under test

Make a throwaway project and add FastAPI and uvicorn to run the API, plus pytest, httpx and Schemathesis as development tools. The ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/api-contract-demo
cd ~/api-contract-demo
uv init --no-package
uv add "fastapi>=0.165,<0.166" "uvicorn>=0.54,<0.55"
uv add --dev "pytest>=9.2,<9.3" "httpx>=0.28,<0.29" "schemathesis>=4.33,<4.34"

Replace the placeholder main.py that uv init created with the API. It keeps a few market-stall products in memory and has four operations: a health check, a paginated list, create, and fetch one by ID. Prices are whole numbers in minor units (kobo, pesewas, cents), the usual way to store money so that no rounding creeps in. This version contains two bugs. Do not look for them yet; finding them is Schemathesis's job.

Bash
cat > main.py <<'PY'
from math import ceil
from typing import Annotated

from fastapi import FastAPI, HTTPException, Path, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, BeforeValidator, Field

app = FastAPI(title="Stall API", version="1.0.0")


def reject_booleans(value):
    # JSON true and false would otherwise be read as 1 and 0.
    if isinstance(value, bool):
        raise ValueError("expected a whole number, not true or false")
    return value


WholeNumber = Annotated[int, BeforeValidator(reject_booleans)]


class ProductIn(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    price: WholeNumber = Field(ge=0, description="Price in minor units, such as kobo or cents")


class Product(ProductIn):
    id: int


class ProductPage(BaseModel):
    items: list[Product]
    page: int
    pages: int


PRODUCTS: dict[int, Product] = {
    1: Product(id=1, name="Rice, 5 kg", price=950000),
    2: Product(id=2, name="Eggs, tray of 30", price=480000),
    3: Product(id=3, name="Palm oil, 1 litre", price=320000),
}

NOT_FOUND = {404: {"description": "No product with that ID"}}
BAD_BODY = {400: {"description": "The body is not valid JSON"}}


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


@app.get("/products")
def list_products(
    page: Annotated[int, Query(ge=1)] = 1,
    per_page: Annotated[int, Query(ge=0, le=50)] = 20,
) -> ProductPage:
    products = list(PRODUCTS.values())
    pages = max(1, ceil(len(products) / per_page))
    start = (page - 1) * per_page
    return ProductPage(items=products[start : start + per_page], page=page, pages=pages)


@app.post("/products", status_code=201, responses=BAD_BODY, response_model=Product)
def create_product(data: ProductIn):
    product = Product(id=max(PRODUCTS, default=0) + 1, **data.model_dump())
    PRODUCTS[product.id] = product
    body = product.model_dump()
    body["price"] = f"{product.price / 100:.2f}"
    return JSONResponse(status_code=201, content=body, headers={"Location": f"/products/{product.id}"})


@app.get("/products/{product_id}", responses=NOT_FOUND)
def get_product(product_id: Annotated[int, Path(ge=1)]) -> Product:
    if product_id not in PRODUCTS:
        raise HTTPException(status_code=404, detail="No product with that ID")
    return PRODUCTS[product_id]
PY

Two details are there on purpose. reject_booleans stops Pydantic's lax mode from accepting true as the number 1, which Schemathesis would otherwise report as invalid data accepted. NOT_FOUND and BAD_BODY add the 404 and 400 responses to the OpenAPI document, because FastAPI only documents 2xx and 422 by itself, and an undocumented status code counts as a failure.

Start the API in your second terminal, from the same folder, and leave it running:

Bash
cd ~/api-contract-demo
uv run uvicorn main:app --port 8000

Check it worked

Back in the first terminal:

Bash
curl -s http://127.0.0.1:8000/health

The reply is {"status":"ok"}, and the second terminal logs a GET /health line with 200 OK.

Step 2 · Write black-box tests with httpx

Black-box tests know only the base URL. A fixture builds one httpx client per test, pointed at API_URL if you set it and at the local API otherwise, so the same suite can run against a staging server later:

Bash
mkdir -p tests
cat > tests/conftest.py <<'PY'
import os

import httpx
import pytest

BASE_URL = os.environ.get("API_URL", "http://127.0.0.1:8000")


@pytest.fixture
def api():
    with httpx.Client(base_url=BASE_URL, timeout=10.0) as client:
        yield client
PY

Now the tests. They cover the routes a client depends on, the 404, and the validation rules, with one parametrised test for four kinds of bad body:

Bash
cat > tests/test_products.py <<'PY'
import pytest


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


def test_list_products_first_page(api):
    response = api.get("/products", params={"per_page": 2})
    assert response.status_code == 200
    body = response.json()
    assert len(body["items"]) == 2
    assert body["page"] == 1
    assert body["pages"] >= 2


def test_get_one_product(api):
    response = api.get("/products/1")
    assert response.status_code == 200
    assert response.json()["name"] == "Rice, 5 kg"


def test_unknown_product_is_404(api):
    response = api.get("/products/999999")
    assert response.status_code == 404


def test_create_product(api):
    response = api.post("/products", json={"name": "Garri, 2 kg", "price": 250000})
    assert response.status_code == 201
    assert response.json()["name"] == "Garri, 2 kg"
    saved = api.get(response.headers["location"])
    assert saved.json()["price"] == 250000


@pytest.mark.parametrize(
    "body",
    [
        {"name": "", "price": 100},
        {"name": "Salt", "price": -1},
        {"name": "Salt"},
        {"name": "Salt", "price": True},
    ],
    ids=["empty-name", "negative-price", "missing-price", "boolean-price"],
)
def test_invalid_product_is_422(api, body):
    response = api.post("/products", json=body)
    assert response.status_code == 422


def test_per_page_above_limit_is_422(api):
    response = api.get("/products", params={"per_page": 51})
    assert response.status_code == 422
PY
uv run pytest -q

Look at test_create_product. It checks the name and the Location header, then reads the product back to check the price. That is a reasonable test, and it is the kind that lets a bug through: nobody checked the price in the create response itself.

Check it worked

pytest prints 10 passed. Every test is green, and the API still has two bugs.

Step 3 · Point Schemathesis at the OpenAPI document

FastAPI serves its OpenAPI document at /openapi.json. List the operations Schemathesis will see:

Bash
curl -s http://127.0.0.1:8000/openapi.json | uv run python -c "import json, sys; doc = json.load(sys.stdin); print('OpenAPI', doc['openapi']); [print(method.upper(), path) for path, ops in doc['paths'].items() for method in ops]"

It prints OpenAPI 3.1.0 and four operations: GET /health, GET /products, POST /products and GET /products/{product_id}.

Schemathesis reads settings from schemathesis.toml in the current folder (or a parent). Create one that switches off a single check. When you send an unsupported method such as DELETE /products, FastAPI's router answers 405 with an Allow header that lists only the first matching route's methods, so the Allow header check fails on every FastAPI app that has GET and POST on one path. That is a framework quirk, not a bug in your code, so turn it off and keep every other check:

Bash
cat > schemathesis.toml <<'TOML'
# FastAPI's 405 responses list only one route's methods in Allow.
[checks]
allow_header_conformance.enabled = false
TOML

Point Schemathesis only at an API you run yourself, or at a test copy. It sends thousands of requests, and POST requests create real records: hundreds of oddly named products here, and the same in any database behind an API. Never run it against production data.

Run it:

Bash
uv run st run http://127.0.0.1:8000/openapi.json

st is Schemathesis's command-line tool. The run goes through four phases. Examples uses any examples in the document; coverage sends boundary and just-outside-the-boundary values for every parameter; fuzzing sends randomly generated valid and invalid requests; stateful chains operations together where the document links them. Every response passes through the checks: no 5xx errors, only documented status codes and content types, bodies that match their schema, invalid input rejected and valid input accepted. Everything runs against your own machine, so after the packages are installed the run costs no mobile data.

Check it worked

The run ends with a red summary line that counts failures, something like 2 failures in 6.12s, and the command exits with status 1. Above it, a failures section lists GET /products with a Server error and POST /products with Response violates schema. Each entry ends with a curl command under "Reproduce with". You may also see an Undocumented status code or Undocumented Content-Type for the same GET /products request: they come from the same crash, which returns a plain-text 500 that the document does not mention.

Step 4 · Read the failures and reproduce them

Start with the server error. The reproduce command Schemathesis prints for GET /products asks for per_page=0. Send it yourself:

Bash
curl -s -o /dev/null -w '%{http_code}\n' 'http://127.0.0.1:8000/products?page=1&per_page=0'

The status is 500. The traceback in the second terminal ends in ZeroDivisionError: division by zero, raised by len(products) / per_page. The parameter is declared ge=0, so the OpenAPI document says 0 is allowed, and the coverage phase always tries the minimum. Nobody writes a hand test for a page size of zero; a generator tries it first.

Now the schema violation. The failure says something like "1800.50" is not of type "integer" at /properties/price, validated against the response schema for status 201. Create a product and read the reply:

Bash
curl -s -X POST http://127.0.0.1:8000/products -H 'Content-Type: application/json' -d '{"name": "Beans, 1 kg", "price": 180050}'
echo

The route formats the price as a string for display, and it returns a JSONResponse itself so it can set the Location header. FastAPI does not validate a response you build yourself against response_model, so the document still promises an integer while the API sends a string. A mobile money app adding up a basket would now be adding text.

Check it worked

The first command prints 500. The second prints a product with "price":"1800.50" in quotes, a string, while GET /products/<id> for the same product returns "price":180050, an integer.

Step 5 · Fix both bugs and add regression tests

Two changes fix the API. per_page must be at least 1, so the document and the code agree that zero is invalid and FastAPI rejects it with a 422. The create route returns the Product model and sets Location through FastAPI's Response parameter, so the price stays an integer and FastAPI validates the body against the model again. Rewrite main.py with both fixes:

Bash
cat > main.py <<'PY'
from math import ceil
from typing import Annotated

from fastapi import FastAPI, HTTPException, Path, Query, Response
from pydantic import BaseModel, BeforeValidator, Field

app = FastAPI(title="Stall API", version="1.0.0")


def reject_booleans(value):
    # JSON true and false would otherwise be read as 1 and 0.
    if isinstance(value, bool):
        raise ValueError("expected a whole number, not true or false")
    return value


WholeNumber = Annotated[int, BeforeValidator(reject_booleans)]


class ProductIn(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    price: WholeNumber = Field(ge=0, description="Price in minor units, such as kobo or cents")


class Product(ProductIn):
    id: int


class ProductPage(BaseModel):
    items: list[Product]
    page: int
    pages: int


PRODUCTS: dict[int, Product] = {
    1: Product(id=1, name="Rice, 5 kg", price=950000),
    2: Product(id=2, name="Eggs, tray of 30", price=480000),
    3: Product(id=3, name="Palm oil, 1 litre", price=320000),
}

NOT_FOUND = {404: {"description": "No product with that ID"}}
BAD_BODY = {400: {"description": "The body is not valid JSON"}}


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


@app.get("/products")
def list_products(
    page: Annotated[int, Query(ge=1)] = 1,
    per_page: Annotated[int, Query(ge=1, le=50)] = 20,
) -> ProductPage:
    products = list(PRODUCTS.values())
    pages = max(1, ceil(len(products) / per_page))
    start = (page - 1) * per_page
    return ProductPage(items=products[start : start + per_page], page=page, pages=pages)


@app.post("/products", status_code=201, responses=BAD_BODY)
def create_product(data: ProductIn, response: Response) -> Product:
    product = Product(id=max(PRODUCTS, default=0) + 1, **data.model_dump())
    PRODUCTS[product.id] = product
    response.headers["Location"] = f"/products/{product.id}"
    return product


@app.get("/products/{product_id}", responses=NOT_FOUND)
def get_product(product_id: Annotated[int, Path(ge=1)]) -> Product:
    if product_id not in PRODUCTS:
        raise HTTPException(status_code=404, detail="No product with that ID")
    return PRODUCTS[product_id]
PY

The changed lines are Query(ge=1, le=50) in list_products and the whole of create_product. The JSONResponse import has gone.

Restart the API so it loads the new code: press Ctrl+C in the second terminal, then run the same command again.

Bash
uv run uvicorn main:app --port 8000

Each bug gets a hand-written test, so it cannot quietly come back even if someone switches Schemathesis off. Append them to the suite and run it:

Bash
cat >> tests/test_products.py <<'PY'


def test_per_page_zero_is_422(api):
    response = api.get("/products", params={"per_page": 0})
    assert response.status_code == 422


def test_create_returns_price_as_integer(api):
    response = api.post("/products", json={"name": "Beans, 1 kg", "price": 180050})
    assert response.status_code == 201
    assert response.json()["price"] == 180050
PY
uv run pytest -q

Check it worked

pytest prints 12 passed. Run the two new tests against the old main.py and both would fail, which is the point of a regression test.

Step 6 · Run Schemathesis again until it is clean

Send the same generated traffic at the fixed API:

Bash
uv run st run http://127.0.0.1:8000/openapi.json

If a new failure appears, read it the same way: copy the reproduce command, confirm it with curl, then decide whether the code or the OpenAPI document is wrong. Sometimes the right fix is in the document, such as a status code the API returns on purpose but never declared.

Check it worked

The summary line is green and reads No issues found in followed by the time, and the command exits with status 0 (echo $? prints 0).

Step 7 · Add a contract test and a CI script

The st command is one way to run Schemathesis in CI. The other is its pytest integration, which turns each operation in the document into a pytest test. Then one pytest run covers both your hand-written tests and the generated ones, with one report:

Bash
cat > tests/test_contract.py <<'PY'
import os

import schemathesis

BASE_URL = os.environ.get("API_URL", "http://127.0.0.1:8000")

schema = schemathesis.openapi.from_url(f"{BASE_URL}/openapi.json", wait_for_schema=30)


@schema.parametrize()
def test_api_matches_its_schema(case):
    case.call_and_validate()
PY
uv run pytest -q

from_url loads the document from the running API, waiting up to 30 seconds for it to come up, and picks up schemathesis.toml the same way the command does. @schema.parametrize() creates one test per operation, and Hypothesis, the property-testing library underneath, feeds each one many generated cases. call_and_validate sends the request and runs every enabled check. A failure prints the same reproduce command as st run.

Now write the script your CI runs. It installs the locked dependencies, starts the API in the background, waits for it, runs pytest and then the full st run with a JUnit report at a fixed path (by default the file name carries a timestamp), and stops the API when it exits, pass or fail, waiting until it has shut down:

Bash
cat > ci.sh <<'SH'
#!/usr/bin/env bash
set -euo pipefail

uv sync --locked
.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 > api.log 2>&1 &
API_PID=$!
# Stop the API and wait until it has shut down, so port 8000 is free.
trap 'kill "$API_PID"; wait "$API_PID" || true' EXIT

for i in $(seq 1 30); do
  if curl -sf http://127.0.0.1:8000/health > /dev/null; then break; fi
  sleep 1
done

uv run pytest -q
uv run st run http://127.0.0.1:8000/openapi.json --report junit --report-junit-path schemathesis-report/junit.xml
SH
chmod +x ci.sh

The script starts its own API on port 8000, so stop the one in your second terminal with Ctrl+C first. Then run it:

Bash
./ci.sh

To use it in GitHub Actions, GitLab CI or any other runner, install uv on the runner, check out the repository and call ./ci.sh. For an API written in another language, replace the uvicorn line with your own server's start command; the tests do not change. Most CI systems can show schemathesis-report/junit.xml as a test report.

Check it worked

pytest prints 16 passed: 12 hand-written tests and one contract test per operation. Then st run ends with No issues found, the script exits with status 0, and schemathesis-report/junit.xml exists. Port 8000 is free again afterwards, because the trap stopped the API.

Step 8 · Clean up

Remove the demo project. Python and uv stay installed:

Bash
cd ~
rm -rf ~/api-contract-demo

Check it worked

ls ~/api-contract-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.