OpenAPI schema export for clients

FastAPI generates an OpenAPI document for free at /openapi.json. The trap is treating that URL as a contract: a router refactor will reshape it without warning. The fix is to export the schema as a versioned artifact your clients pull, so the contract evolves on your release schedule, not on whatever shipped to main last night.

scripts/export_openapi.py
python
import json
import pathlib
from main import app

VERSION = 'v1'
OUT = pathlib.Path(f'openapi/{VERSION}.json')


def main() -> None:
    OUT.parent.mkdir(parents=True, exist_ok=True)
    schema = app.openapi()
    schema['info']['version'] = VERSION
    OUT.write_text(json.dumps(schema, indent=2, sort_keys=True))
    print(f'wrote {OUT}')


if __name__ == '__main__':
    main()

Export under openapi/v1.json. Frontends and SDK generators target the versioned path, not the live /openapi.json that changes whenever a route does.

Two rules keep this honest. The export script runs in CI and fails the build if the committed openapi/v1.json drifts from the current router. And a version bump is intentional: a renamed field or a new required parameter goes into v2.json before any client is asked to migrate.

Quiz: Quiz

Loading practice…