Contract Tests Generated from an OpenAPI Document
Generate property-based contract tests automatically from your OpenAPI specification with Schemathesis, and discover how consumer-driven contract tests with Pact prevent breaking changes.
Contentsand lesson path
On this page
- Why it matters
- Property-based contract testing with Schemathesis
- Consumer-driven contracts with Pact
- Check your understanding
- Apply it
- Review prompt
Lessons of API Integration & Contract Testing
- Why Mocks Lie About Databases Concept · 15 min
- Lab: A Disposable PostgreSQL for Every Test Run Lab · 30 min
- End-to-End API Tests with Factories Worked example · 25 min
- Contract Tests Generated from an OpenAPI Document Worked example · 25 min
- Fast, Deterministic, Not Flaky Concept · 15 min
- Check: Diagnose the Failing Suite Knowledge check · 8 questions
What you will learn
- Check the implementation against its OpenAPI contract with schema-based tests, and explain where consumer-driven contract tests fit.
Prerequisites: Software Testing Fundamentals, Data Access with SQLAlchemy
01. Why it matters
FastAPI generates an OpenAPI document (/openapi.json) from your route decorators and Pydantic models. Client teams and SDK generators treat it as the contract: what they may send and what they get back.
The document and the server can still disagree. Hand-written tests check the cases someone thought of, not unusual inputs. If a large number or an odd string causes a 500, or a response leaves out a field the schema promises, clients break. Schema-based contract testing turns the OpenAPI document itself into test cases.
In CI, every commit is then checked against the schema on generated inputs. This samples inputs rather than proving conformance, so it can miss stateful bugs, rare inputs and rules the schema cannot express. And when FastAPI generates the schema from the same code, the test checks self-consistency; to catch breaking changes, also compare the generated /openapi.json with the published copy in CI.
02. Property-based contract testing with Schemathesis
Schemathesis is a property-based testing tool built on top of the Hypothesis framework. Property-based means you state rules that every response must follow, and the tool generates the inputs. Schemathesis reads your OpenAPI document, looks at the parameter schemas, data types and constraints, and generates many valid and invalid HTTP requests for each operation.
Every response then goes through a set of checks, all enabled by default (Schemathesis checks reference). Three of them matter most here:
- No server errors (
not_a_server_error): whatever the input, the server must answer with a success or a client error such as 400 or 422, never a 5xx from an unhandled exception. - Response conformance (
response_schema_conformance): the body must validate against the JSON schema declared for that status code in the OpenAPI document. - Status code conformance (
status_code_conformance): the server must not return a status code that the document does not list for the operation.
Other default checks compare content types and headers, and test that invalid data is rejected and valid data accepted.
import pytest
import schemathesis
from fastapi.testclient import TestClient
from hypothesis import HealthCheck, settings
from sqlalchemy.orm import Session
from app.main import app
from tests.factories import make_user
# Load the OpenAPI document straight from the FastAPI app, in-process
schema = schemathesis.openapi.from_asgi("/openapi.json", app)
@pytest.fixture
def auth(session: Session) -> dict[str, str]:
"""A real user inside the test transaction, so protected routes pass the 401."""
user = make_user(session)
session.commit() # releases the savepoint, so a later rollback keeps this user
return {"Authorization": f"Bearer {user.raw_token}"}
@schema.parametrize()
@settings(suppress_health_check=[HealthCheck.function_scoped_fixture])
def test_api_conforms_to_openapi(
case: schemathesis.Case, client: TestClient, auth: dict[str, str]
) -> None:
# `client` installs the get_session override from Lesson 2, so every
# generated request runs inside the test's rolled-back transaction.
case.call_and_validate(headers=auth)This file goes into the reading-list project from the lab and the previous lesson; install the tool with uv pip install schemathesis==4.34.2 hypothesis==6.170.17. Pin both: other versions add checks and generate other inputs. The runs below used these pins with FastAPI 0.163.1 (0.165.0 gave the same results), Pydantic 2.14.4 and PostgreSQL 17.12.
schemathesis.openapi.from_asgi("/openapi.json", app) loads the schema from the app itself, and generated requests reach FastAPI directly through ASGI, the interface between Python web servers and apps. No Uvicorn server and no network port are involved.
The fixtures matter as much as the test. client (from the lab) installs the get_session override, so generated requests write inside the test's rolled-back transaction instead of reaching the database in DATABASE_URL. auth creates one real user, so protected routes get past the 401. Schemathesis runs one pytest test per operation, and Hypothesis reuses function-scoped fixtures for every request in that test. The health check that warns about this is suppressed on purpose: one user and one transaction per operation is what this test wants (Schemathesis: testing Python apps). Run it:
pytest -q --no-header tests/test_contracts.pyFF.F [100%]
__________________ test_api_conforms_to_openapi[POST /users] ___________________
ExceptionGroup: Hypothesis found 2 distinct failures in explicit examples. ...
- ST103 Undocumented status code
Received: 409
Documented: 201, 422
psycopg.errors.StringDataRightTruncation: value too long for type character varying(254)
__________________ test_api_conforms_to_openapi[POST /books] ___________________
ExceptionGroup: Hypothesis found 4 distinct failures in explicit examples. ...
- ST205 Allow header mismatch
`Allow: POST` does not match the schema. Missing documented methods: GET
- ST103 Undocumented status code
Received: 409
psycopg.errors.NumericValueOutOfRange: integer out of range
[parameters: {'owner_id': 4, 'title': '', 'slug': '', 'year': 9223372036854775808}]
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back ...
______________ test_api_conforms_to_openapi[GET /books/{book_id}] ______________
ExceptionGroup: Hypothesis found 3 distinct failures in explicit examples. ...
- ST103 Undocumented status code
Received: 404
psycopg.errors.NumericValueOutOfRange: integer out of range
curl -X GET -H 'Authorization: [Filtered]' http://testserver/books/9223372036854775808
psycopg.errors.InFailedSqlTransaction: current transaction is aborted ...
FAILED tests/test_contracts.py::test_api_conforms_to_openapi[POST /users] - E...
FAILED tests/test_contracts.py::test_api_conforms_to_openapi[POST /books] - E...
FAILED tests/test_contracts.py::test_api_conforms_to_openapi[GET /books/{book_id}]
3 failed, 1 passed in 15.25sThe first run fails three of the four operations. All of them come from the explicit examples, boundary values derived from the schema, so this part repeats exactly. They are of three kinds.
- Real bugs that only the real database reveals. The schema says
emailis any string, but the column isvarchar(254), so a longer address reaches PostgreSQL, which rejects it with aDataError.yearand the path parameterbook_idare any integer, but both columns are 32-bitinteger, so the boundary value 9223372036854775808 fails inside the query.save()catches onlyIntegrityError, so each of these ends as a 500. A mock would have accepted all three, and SQLite, which ignoresvarcharlengths and stores integers up to 2^63 − 1, would have hidden the long strings and large years, as the first lesson warned. - Failures caused by an earlier failure. After a
DataError, the test's shared session and its transaction refuse more work until a rollback, so the next generated request in the same test fails withPendingRollbackErrororInFailedSqlTransaction. In production each request gets a fresh session, so these are not new bugs. But they can hide one: the request behind thePendingRollbackErrorsent a very long title, andtitleisvarchar(200). - Responses the contract does not list. Both POST routes answer 409 for a duplicate and
GET /books/{book_id}answers 404, but no decorator declares them (ST103, undocumented status code). One more comes from the framework:GET /booksandPOST /booksare separate route functions, so the 405 answer toOPTIONS /bookslists onlyPOSTin itsAllowheader (ST205).
Fix the database limits where the contract lives, in the API models, so they appear in /openapi.json and bad input gets a 422 instead of a 500: max_length on email and title, a range on year, and Path(ge=1, le=2**31 - 1) on book_id. Declare the 404 and 409 with responses= on the decorator (FastAPI: additional responses). Rerun after each change: a failure can hide the next one. Once the explicit examples pass, the random phase reaches rarer inputs. In these runs it found three more problems:
- a body made of NUL bytes, which FastAPI answers with an undocumented
400("There was an error parsing the body"); - a title containing a NUL character, which PostgreSQL text columns refuse, so the API answered 500;
trueaccepted as the year 1, because Pydantic's lax mode converts booleans to integers (ST201, schema-violating request accepted).
The random findings do not appear on every run. Decide each one on purpose: fix the code, document the response, or switch the check off with excluded_checks= and a comment that says why. Here the 400 is documented for the whole app, a pattern and a validator turn the NUL and boolean cases into 422s, and the Allow mismatch is accepted, because no client of this API reads Allow. A strict year field is the wrong fix: JSON Schema counts 1.0 as an integer, so Schemathesis then reports ST202, a schema-valid request rejected. Replace parts 1 and 3 of app/main.py (part 2 is unchanged):
import re
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Path
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.deps import get_session
from app.models import Book, User
from app.security import hash_password, hash_token, new_token
app = FastAPI(responses={400: {"description": "Body could not be parsed"}})
DB = Annotated[Session, Depends(get_session)]
NO_NUL = r"^[^\x00]*$" # PostgreSQL text columns refuse the NUL character
class SignUp(BaseModel):
email: str = Field(max_length=254, pattern=NO_NUL) # varchar(254)
password: str
class BookIn(BaseModel):
title: str = Field(max_length=200, pattern=NO_NUL) # varchar(200)
year: int = Field(ge=1, le=9999) # fits the 32-bit integer column
@field_validator("year", mode="before")
@classmethod
def reject_booleans(cls, value: object) -> object:
if isinstance(value, bool): # lax mode would read true as 1
raise ValueError("year must be a number, not true or false")
return value@app.post("/users", status_code=201,
responses={409: {"description": "Email already registered"}})
def sign_up(body: SignUp, db: DB) -> dict:
token = new_token()
user = User(email=body.email, password_hash=hash_password(body.password),
token_hash=hash_token(token))
save(db, user, "email already registered")
return {"id": user.id, "email": user.email, "token": token}
@app.post("/books", status_code=201,
responses={409: {"description": "You already have this title"}})
def create_book(body: BookIn, db: DB,
user: Annotated[User, Depends(current_user)]) -> dict:
book = Book(owner_id=user.id, title=body.title,
slug=make_slug(body.title), year=body.year)
save(db, book, "you already have a book with this title")
return {"id": book.id, "title": book.title, "year": book.year}
@app.get("/books")
def list_books(db: DB, user: Annotated[User, Depends(current_user)]) -> list[dict]:
books = db.scalars(select(Book).where(Book.owner_id == user.id)
.order_by(Book.id))
return [{"id": b.id, "title": b.title, "year": b.year} for b in books]
@app.get("/books/{book_id}", responses={404: {"description": "Book not found"}})
def read_book(book_id: Annotated[int, Path(ge=1, le=2**31 - 1)], db: DB,
user: Annotated[User, Depends(current_user)]) -> dict:
book = db.get(Book, book_id)
if book is None or book.owner_id != user.id:
raise HTTPException(404, "book not found")
return {"id": book.id, "title": book.title, "year": book.year} # GET and POST /books are separate routes, so a 405 lists only one method
# in Allow. Accepted on purpose: no client of this API relies on Allow.
case.call_and_validate(
headers=auth,
excluded_checks=[schemathesis.checks.allow_header_conformance],
)rm -rf .hypothesis && pytest -q --no-header tests/test_contracts.py.... [100%]
4 passed in 20.34sRemoving .hypothesis deletes the failing examples Hypothesis saved, so the run starts fresh. Six fresh runs of this fixed version passed; the lab tests from Lessons 2 and 3 still pass too.
Two limits apply to any result. Response checks are only as strict as the schema: these routes return a plain dict, so the documented body is "any object", and a response_model would make the body check meaningful. And generation samples inputs: a passing run means these inputs found nothing, not that none exist.
03. Consumer-driven contracts with Pact
Schema-based testing checks that the provider follows its own OpenAPI document. It cannot tell you which fields and endpoints your consumers actually use.
When several clients call the same backend, removing or renaming a field that nobody thought was used can break one of them in production. Consumer-driven contract testing (CDC), best known from the tool Pact, closes this gap in three steps:
- The consumer writes a test against a local mock server provided by Pact, recording the requests it sends and the response fields it needs.
- Pact saves these expectations as a JSON contract (a "pact file") and publishes it to a shared Pact Broker.
- In the provider's CI build, Pact fetches the consumers' contracts from the broker and replays each recorded interaction against the running backend. If a change breaks a contract that a consumer relies on, the provider build fails before deployment.
When to use which:
- Schemathesis (provider side, generated inputs) checks that your service behaves as its OpenAPI document says and finds crashes on boundary inputs. It suits public APIs whose consumers are unknown.
- Pact (consumer-driven contracts) suits internal services with known consumers. It catches breaking changes across team boundaries before deployment and records which consumer depends on what, without a full end-to-end environment. The two complement each other.
04. Check your understanding
05. Apply it
Start again from the first version of app/main.py and make the fixes one at a time, rerunning after each, so you see which failure each fix removes and which new one appears. Then give GET /books/{book_id} a response_model with id, title and year, rerun, and check that the body check now has something to compare. Keep a list of what you changed and why: it is the review record for your contract. In the next lesson, you will learn techniques for keeping your integration suite fast, deterministic, and free from flaky tests.
06. Review prompt
Explain how property-based testing with Schemathesis differs from traditional example-based testing. Describe the workflow of consumer-driven contract testing with Pact, and explain why an API might pass 100% of its OpenAPI schema checks yet still break a mobile client in production.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.