← Back to FastAPI, page 5

fastapi-0096 · Hard senior

How do you detect breaking API changes in FastAPI using OpenAPI snapshots and contract tests in CI?

Export app.openapi() to a committed snapshot file and compare the new schema with the main-branch version in CI. A diff tool classifies changes: removed paths or methods, removed or retyped response fields, new required request parameters or properties, narrowed enums and changed status codes are breaking; added optional fields and new endpoints are not. Fail the build on breaking changes unless the version is bumped deliberately. Add consumer-driven contract tests for critical clients.

Full answer

Why: FastAPI generates the OpenAPI schema from code, so a harmless refactor (renamed field, changed type annotation) silently changes the public contract. Clients and generated SDKs break in production.

Pipeline:

  1. python -c "import json, app; print(json.dumps(app.app.openapi(), indent=2, sort_keys=True))" > openapi.json, committed to the repository. Sorted keys keep diffs readable and stable.
  2. A test regenerates the schema and compares it with the committed snapshot; if different, it fails with a message to update the snapshot (a conscious, reviewed change). This catches unintended changes.
  3. A CI job compares the snapshot with the target branch (or last release) using a diff tool: oasdiff breaking old.json new.json, openapi-diff, or Optic. Breaking changes block the merge unless labelled for a new major version.
  4. Optional: schema-based fuzzing (Schemathesis) runs generated requests against the app (with TestClient or a running service) and checks every response against the declared schema, finding 500s and schema violations.
  5. Consumer-driven contracts (Pact) let important clients publish their expectations, which provider tests verify.

Classification rules (what the custom diff in the snippet checks):

  • Breaking for responses: removed field, type change, field becoming nullable or optional that was required, removed status code that clients depend on, narrowed or widened enums (consumers with exhaustive switches break on new values: document this policy).
  • Breaking for requests: new required parameter or property, removed accepted values, tightened constraints (new maxLength), changed type.
  • Non-breaking: new endpoints, new optional request fields, new response fields (if clients ignore unknown fields), looser constraints on requests.

Keep operationIds stable, since generated clients use them. Use deprecation windows before removals, and keep version-specific routers (/v1) for unavoidable breaks.

python
from fastapi import FastAPI
from pydantic import BaseModel


def build(version):
    app = FastAPI(title="Campus", version=version)

    class StudentV1(BaseModel):
        id: int
        name: str
        marks: int

    class StudentV2(BaseModel):
        id: int
        name: str
        marks: str                              # type change: breaking
        email: str | None = None                # new optional field: fine

    Student = StudentV1 if version == "1" else StudentV2

    @app.get("/students/{sid}")
    def get_student(sid: int) -> Student:
        ...

    if version == "1":
        @app.get("/legacy")
        def legacy():
            return {}

    @app.get("/search")
    def search(q: str = "", page: int | None = None, region: str = "" if version == "1" else ...):
        return []

    return app.openapi()


def resolve(schema, node):
    ref = node.get("$ref")
    return schema["components"]["schemas"][ref.split("/")[-1]] if ref else node


def properties(schema, op):
    body = op["responses"]["200"]["content"]["application/json"]["schema"]
    node = resolve(schema, body)
    return {k: v.get("type") or [t.get("type") for t in v.get("anyOf", [])] for k, v in node.get("properties", {}).items()}


def breaking_changes(old, new):
    problems = []
    for path, methods in old["paths"].items():
        if path not in new["paths"]:
            problems.append(f"removed path {path}")
            continue
        for method, op in methods.items():
            if method not in new["paths"][path]:
                problems.append(f"removed {method.upper()} {path}")
                continue
            new_op = new["paths"][path][method]
            old_params = {p["name"]: p for p in op.get("parameters", [])}
            for p in new_op.get("parameters", []):
                if p.get("required") and (p["name"] not in old_params or not old_params[p["name"]].get("required")):
                    problems.append(f"{method.upper()} {path}: parameter {p['name']!r} became required")
            if "200" in op["responses"] and "content" in op["responses"]["200"]:
                before, after = properties(old, op), properties(new, new_op)
                for field, kind in before.items():
                    if field not in after:
                        problems.append(f"{path}: response field {field!r} removed")
                    elif after[field] != kind:
                        problems.append(f"{path}: response field {field!r} changed {kind} -> {after[field]}")
    return problems


v1, v2 = build("1"), build("2")
for line in breaking_changes(v1, v2):
    print("BREAKING:", line)
print("v1 vs v1:", breaking_changes(v1, v1))
print("added in v2 (not breaking):", sorted(properties(v2, v2["paths"]["/students/{sid}"]["get"])) )

Standalone script. Run it with `python file.py`; it builds two schema versions in memory and diffs them. In CI use a maintained tool such as oasdiff instead of the small diff shown here. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): BREAKING: /students/{sid}: response field 'marks' changed integer -> string BREAKING: removed path /legacy BREAKING: GET /search: parameter 'region' became required v1 vs v1: [] added in v2 (not breaking): ['email', 'id', 'marks', 'name']

Key points

  • Commit a sorted OpenAPI snapshot and fail on unreviewed changes
  • Run a breaking-change diff (oasdiff, openapi-diff) against the main branch
  • New required inputs and removed or retyped outputs are breaking
  • Fuzz with Schemathesis to validate responses against the schema
  • Keep operationIds stable; deprecate before removing

Common mistakes

  • Treating the generated schema as an implementation detail
  • No snapshot or diff in CI
  • Removing fields without a deprecation window
  • Letting operationIds change on refactors
  • Testing only happy paths against the schema

Follow-ups

  • How would you use Schemathesis in CI?
  • How do consumer-driven contracts differ from schema diffs?
  • How should enum additions be treated?

Tips

  • Describe the pipeline
  • Classify breaking vs non-breaking
  • Mention operationId stability