{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"\ud83e\udde9 openapi-first \u2014 OpenAPI as the Single Source of Truth","text":"

openapi-first is a small, strict library for OpenAPI-first FastAPI bootstrapping: the OpenAPI document is the application contract \u2014 not an afterthought generated from decorators)Skip. Routes, schemas, security, and even the HTTP client are all derived from one specification.

Doc model: this wiki is written for humans \u2014 how-to guides, examples, and usage recipes. The authoritative API contracts live in the code (docstrings) and the machine-readable bundle under docs/mcp/.

"},{"location":"#key-features","title":"\ud83d\ude80 Key Features","text":""},{"location":"#installation","title":"\ud83d\udce6 Installation","text":"

From your internal PyPI:

pip install --extra-index-url https://$PYPI_USERNAME:$PYPI_PASSWORD@pip.aetoskia.com/simple openapi-first\n

From local source:

pip install -e .\n
"},{"location":"#documentation-structure","title":"\ud83d\udcc1 Documentation Structure","text":"Section Description Overview The mental model: spec as contract, operationId binding, fail-fast guarantees Components app, binder, loader, client, errors, security, codegen, cli Use cases Step-by-step recipes \u00b7 01 \u2013 Quickstart Scaffold your first OpenAPI-first service \u00b7 02 \u2013 Templates The bundled application templates and how to use them \u00b7 03 \u2013 Client setup Build an operationId-driven HTTP client \u00b7 04 \u2013 Codegen Generate Pydantic models and route stubs from a spec Design Architecture, responsibilities, and startup pipeline Security securitySchemes, env resolution, and JWT introspection Error Handling The error hierarchy and when each error is raised Testing Test strategy, quality gates, and coverage"},{"location":"#related-resources","title":"\ud83d\udd17 Related Resources","text":"

\u00a9 Aetoskia Internal \u2014 openapi-first 0.0.6

"},{"location":"01_overview/","title":"Overview \u2014 The OpenAPI-First Mental Model","text":"

openapi-first inverts the usual FastAPI workflow. Instead of decorating routes in code and letting FastAPI invent an OpenAPI document for you, you write one OpenAPI document first and let the library assemble both the application and the client from it. The spec is the contract; code is the implementation.

"},{"location":"01_overview/#1-the-mental-model","title":"\ud83e\udde0 1. The Mental Model","text":""},{"location":"01_overview/#11-one-source-of-truth","title":"1.1 One source of truth","text":"

Your OpenAPI document (openapi.yaml or openapi.json) is the single authoritative contract:

paths:\n  /health:\n    get:\n      operationId: get_health\n      responses:\n        \"200\":\n          description: OK\n          content:\n            application/json:\n              schema:\n                type: object\n

Every route, method, parameter, schema, and security requirement lives here \u2014 and only here. Code never declares routes.

"},{"location":"01_overview/#12-operationid-is-the-binding-key","title":"1.2 operationId is the binding key","text":"

The only bridge between the spec and your Python code is the operationId. Each operation maps, by name, to exactly one plain callable:

# routes.py\ndef get_health():\n    \"\"\"Health check operation handler.\"\"\"\n    return {\"status\": \"ok\"}\n

openapi_first resolves operationId: get_health \u2192 routes.get_health and registers the route. No decorators, no @app.get, no routing metadata in code.

Guarantees this binding provides:

"},{"location":"01_overview/#13-fail-fast-by-design","title":"1.3 Fail-fast by design","text":"

Contract violations are detected at application startup (or client construction), never silently at request time:

What goes wrong When it fails Invalid / unloadable spec load_openapi at startup Spec fails OpenAPI 3.x validation load_openapi at startup operationId missing a handler bind_routes at startup Operation declared but no operationId bind_routes at startup Missing / duplicate operationId in client OpenAPIClient(...) construction"},{"location":"01_overview/#2-what-it-looks-like","title":"\u2699\ufe0f 2. What It Looks Like","text":""},{"location":"01_overview/#21-scaffold-an-application","title":"2.1 Scaffold an application","text":"
openapi-first scaffold health_app my-health-service\nopenapi-first scaffold --list\n

scaffold copies a bundled template (verbatim \u2014 no code generation, no mutation) into a directory of your choice.

"},{"location":"01_overview/#22-bootstrap-the-server","title":"2.2 Bootstrap the server","text":"
# main.py\nfrom openapi_first.app import OpenAPIFirstApp\nimport routes\n\napp = OpenAPIFirstApp(\n    openapi_path=\"openapi.yaml\",\n    routes_module=routes,\n    title=\"My Service\",\n)\n

Run with your FastAPI-compatible server (ASGI):

uvicorn main:app --reload\n

FastAPI itself drives the server; every route, response model, and security dependency comes from the spec. /openapi.json and Swagger UI always reflect the spec, byte-for-byte.

"},{"location":"01_overview/#23-talk-to-it-with-the-client","title":"2.3 Talk to it with the client","text":"
# client-side\nfrom openapi_first.loader import load_openapi\nfrom openapi_first.client import OpenAPIClient\n\nspec = load_openapi(\"openapi.yaml\")\nclient = OpenAPIClient(spec)\n\nresponse = client.get_health()          # operationId-driven call\nprint(response.status_code)             # 200\nprint(response.json())                  # {\"status\": \"ok\"}\n

OpenAPIClient builds one callable per operationId from the same spec, so the client can never drift from the server.

"},{"location":"01_overview/#3-where-things-live","title":"\ud83e\udde9 3. Where Things Live","text":"Concern Module Load + validate spec openapi_first.loader Boot FastAPI app openapi_first.app Bind routes by opId openapi_first.binder HTTP client openapi_first.client Error hierarchy openapi_first.errors Security dependencies openapi_first.security Pydantic model codegen openapi_first.codegen (uses datamodel_code_generator) Route stub codegen openapi_first.codegen_routes Models / routes CLI openapi_first.cli Bundled templates openapi_first.templates

Jurisdictions:

"},{"location":"01_overview/#4-the-non-goals","title":"\ud83d\udcc4 4. The Non-Goals","text":"

openapi-first deliberately does not:

"},{"location":"01_overview/#5-path-forward","title":"\ud83e\udded 5. Path Forward","text":"

New here? Start with 01 \u2013 Quickstart. Want to copy a runnable app? Jump to 02 \u2013 Templates. Digging into internals? See Design.

"},{"location":"01_overview/#related","title":"Related","text":""},{"location":"02_components/","title":"Components \u2014 What Ships in the Box","text":"

The library is deliberately small. Everything you need to run an OpenAPI-first service and talk to it with a strict client fits in a handful of modules.

"},{"location":"02_components/#1-module-map","title":"\ud83d\uddc2\ufe0f 1. Module Map","text":"Module Responsibility Import openapi_first.loader Load/validate the spec, resolve {ENV_VAR} load_openapi openapi_first.app OpenAPI-first FastAPI application bootstrap OpenAPIFirstApp openapi_first.binder Spec \u2192 route binding via operationId bind_routes openapi_first.client operationId-driven HTTP client OpenAPIClient openapi_first.errors Explicit error hierarchy OpenAPIFirstError, OpenAPIClientError, MissingOperationHandler openapi_first.security Security-dependency construction from the spec parse_security_schemes, make_security_dependencies openapi_first.codegen Pydantic model generation (build-time) generate_models openapi_first.codegen_routes Route-handler stub generation (build-time) generate_routes openapi_first.cli scaffold / models / routes command surface CLI entry point openapi_first.templates Copyable application templates (NOT library API) openapi-first scaffold"},{"location":"02_components/#2-loader-load-validate","title":"\u2699\ufe0f 2. loader \u2014 Load & Validate","text":"

load_openapi(path: str | Path) -> dict[str, Any] (in openapi_first/loader.py).

loader.py ensures a spec is real, readable, parseable, and schema-valid before anything else runs \u2014 a golden rule of fail-fast.

from openapi_first.loader import load_openapi\n\nspec = load_openapi(\"openapi.yaml\")\n

Behavior:

Env-var resolution lives at the security layer rather than the loader (see Security).

"},{"location":"02_components/#3-app-the-application-bootstrap","title":"\ud83e\uddec 3. app \u2014 The Application Bootstrap","text":"

OpenAPIFirstApp (in openapi_first/app.py) is a FastAPI subclass that replaces manual route registration with OpenAPI-driven binding.

from openapi_first.app import OpenAPIFirstApp\nimport routes\n\napp = OpenAPIFirstApp(\n    openapi_path=\"openapi.yaml\",\n    routes_module=routes,\n    title=\"My Service\",\n)\n

Startup pipeline (fail-fast, in this order):

  1. Load the spec (.yaml/.json).
  2. Validate it against OpenAPI 3.x schema.
  3. Parse securitySchemes and per-operation security.
  4. Build per-route security dependencies.
  5. Bind every path/method \u2192 handler by operationId; a missing handler, a missing operationId on a declared operation, or an unbound operation raises at startup.

Guarantees:

Keyword arguments beyond openapi_path / routes_module pass straight through to fastapi.FastAPI (it's a subclass \u2014 title, version, middleware, lifespan, \u2026 all work).

"},{"location":"02_components/#4-binder-spec-route-binding","title":"\ud83d\udd17 4. binder \u2014 Spec \u2192 Route Binding","text":"

bind_routes(app, spec, routes_module, security_deps=None) -> None (in openapi_first/binder.py).

This is the heart of the OpenAPI-first guarantee. For each path + HTTP method in the spec:

  1. Reads the operation's operationId.
  2. Looks up routes_module.<operationId> \u2014 a plain callable.
  3. Registers a FastAPI APIRoute bound to that handler, injecting Depends(...) for any matching security requirements.

Failures are explicit and early:

Condition Raised No operationId on an operation MissingOperationHandler operationId has no handler function MissingOperationHandler A path/method declared but unbound MissingOperationHandler

Handlers stay framework-agnostic: they're plain functions (payload, id, response) named after operationIds \u2014 no decorators, no routing metadata.

"},{"location":"02_components/#5-client-the-other-side-of-the-contract","title":"\ud83d\udce1 5. client \u2014 The Other Side of the Contract","text":"

OpenAPIClient(spec, base_url=None, client=None) (in openapi_first/client.py).

The same spec that builds the server builds its client \u2014 one callable per operationId, keyed by name:

from openapi_first.loader import load_openapi\nfrom openapi_first.client import OpenAPIClient\n\nspec = load_openapi(\"openapi.yaml\")\nclient = OpenAPIClient(spec)\n\nresponse = client.get_health()\nresponse = client.get_user(path_params={\"user_id\": 1})\nresponse = client.create_user(body={\"name\": \"Ada\"})\n

How operations become methods:

Client-construction guarantees (fail-fast, same philosophy as the app):

Construction errors raise OpenAPIClientError; request-time errors surface as httpx exceptions with operationId context.

"},{"location":"02_components/#6-errors-explicit-error-hierarchy","title":"\ud83d\udca5 6. errors \u2014 Explicit Error Hierarchy","text":"

Everything raised by openapi-first derives from OpenAPIFirstError (in openapi_first/errors.py), so callers can handle first-party failures with a single except:

See Error Handling for the full table.

"},{"location":"02_components/#7-security-auth-from-the-spec","title":"\ud83d\udee1\ufe0f 7. security \u2014 Auth from the Spec","text":"

security.py turns an OpenAPI securitySchemes section into FastAPI Depends(...) objects \u2014 no manual middleware.

Supported scheme types (extensible):

Key properties: resolution is per-operation, env placeholders resolve once at startup, and dependencies are injected by binder \u2014 your handlers never mention security.

"},{"location":"02_components/#8-codegen-cli-build-time-tooling","title":"\ud83c\udfed 8. codegen & cli \u2014 Build-Time Tooling","text":"

Generation is strictly build-time \u2014 spec \u2192 code, run once by a developer, committed:

"},{"location":"02_components/#openapi-first-models-spec-o-file","title":"openapi-first models <spec> -o <file>","text":"

Generates Pydantic models from spec schemas (wraps datamodel_code_generator):

# cli path\nopenapi-first models openapi.yaml -o app/models.py\n
"},{"location":"02_components/#openapi-first-routes-spec-o-dir-use-models-models-module-models","title":"openapi-first routes <spec> -o <dir> [--use-models] [--models-module models]","text":"

Generates one routes_<resource>.py stub file per resource, with NotImplementedError handlers bound to operationIds (optionally importing your generated models):

openapi-first routes openapi.yaml -o app/routes --use-models\n
"},{"location":"02_components/#openapi-first-scaffold-template-path","title":"openapi-first scaffold <template> [path]","text":"

Copies a bundled application template verbatim (see Templates).

"},{"location":"02_components/#9-templates-copyable-applications","title":"\ud83e\uddf1 9. templates \u2014 Copyable Applications","text":"

Four bundled, runnable applications live under openapi_first/templates/: health_app, crud_app, model_app, and vet_app. They are not part of the library API \u2014 no lint/format/type gates, never imported at runtime. They exist to be copied via:

openapi-first scaffold <template> [target-dir]\nopenapi-first scaffold --list\n
"},{"location":"02_components/#related","title":"\ud83d\udd17 Related","text":""},{"location":"04_design/","title":"Design \u2014 Guarantees, Startup Pipeline, and the Contract Model","text":"

This page is the architecture reference: the fail-fast startup surface, the guarantees that hold by construction, and the trade-offs baked into every decision.

"},{"location":"04_design/#1-the-startup-pipeline","title":"\ud83c\udfd7\ufe0f 1. The Startup Pipeline","text":"

Everything happens once, eagerly, at construction time \u2014 for the app at OpenAPIFirstApp(...), for the client at OpenAPIClient(...). There is no lazy loading, no deferred binding, no \"it'll work on first request\".

openapi.yaml \u2500\u2500\u25ba loader.load_openapi\n                     \u251c\u2500 parse (json/yaml by extension)\n                     \u251c\u2500 validate (strict OpenAPI 3.x validator)\n                     \u2514\u2500\u25ba dict                       \u2500\u2500\u25b6 OpenAPISpecLoadError\n                             \u2502\nOpenAPIFirstApp(openapi_path=..., routes_module=routes)\n    \u251c\u2500 1. load + validate spec (loader)\n    \u251c\u2500 2. parse securitySchemes (security)\n    \u251c\u2500 3. make_security_dependencies (security)\n    \u251c\u2500 4. bind_routes: every operationId \u2500\u2500\u25ba routes.<operationId>\n    \u2502        \u2514\u2500 missing op / missing handler \u2500\u2500\u25ba MissingOperationHandler\n    \u2514\u2500\u25ba FastAPI app: routes registry + /openapi.json + Swagger UI\n

Client \u2014 same spec, same guarantees:

OpenAPIClient(spec)\n    \u251c\u2500 require servers[]\n    \u251c\u2500 require paths\n    \u251c\u2500 one callable per operationId (client.<operationId>)\n    \u2502    \u2514\u2500 missing / duplicate opId \u2500\u2500\u25ba OpenAPIClientError\n    \u2514\u2500\u25ba ready\n
"},{"location":"04_design/#2-guarantees-that-hold-by-construction","title":"\ud83d\udcdc 2. Guarantees That Hold by Construction","text":"

These are not conventions \u2014 they are enforced at startup or client construction:

  1. Every route is spec-declared. Routes are registered only from paths; there is no decorator-driven or implicit routing.
  2. Every operation is handled. Each operationId resolves to an exact handler name in routes_module; a missing one aborts bootstrap.
  3. Every operation has an operationId. An operation without one cannot be bound and fails fast.
  4. Client and server use the same spec. One document drives both sides, so they cannot drift.
  5. Auth is spec-driven. security dependencies come from securitySchemes + per-operation security; no manual middleware.
  6. Spec is valid before use. Invalid, malformed, or unloadable specs are rejected at load, not at first request.
"},{"location":"04_design/#the-startup-no-half-states-property","title":"The startup \"no half-states\" property","text":"

Because binding, validation, and security resolution all run at construction, a booted app is a provably-complete app. If the contract is violated in any way, the process refuses to start \u2014 the failure is loud, immediate, and tells you exactly what to fix.

"},{"location":"04_design/#3-component-responsibilities","title":"\ud83e\udde9 3. Component Responsibilities","text":"Module Owns Refuses to loader parse + validate the spec modify or \"fix\" the spec app assemble FastAPI from spec + handlers routing decisions, decorators binder operationId \u2192 handler mapping infer handlers from paths client build one callable per operationId guess URLs, deserialize implicitly security schemes \u2192 FastAPI Depends manual middleware errors the error hierarchy swallow failures codegen build-time model/routes generation runtime codegen templates copyable scaffolds production data stores

Rule of thumb for contributors: keep modules coercive (they raise if the contract is wrong) and narrow (one responsibility each). Pydoclint + the test suite keep that contract honest.

"},{"location":"04_design/#4-design-trade-offs-accepted","title":"\u2696\ufe0f 4. Design Trade-offs (Accepted)","text":"Decision Chosen because What you give up Handlers are plain callables Framework-agnostic, testable, grep-able No decorator sugar Fail-fast at startup Drift caught in CI, not at 3am Slightly heavier boot Raw httpx.Response from client No hidden deserialization/validation You read .json() yourself Build-time codegen One-way generation, no runtime generator dep Spec must already be spec-valid Templates copy verbatim Scaffold, not magic Templates never updated in place"},{"location":"04_design/#related","title":"\ud83d\udd17 Related","text":""},{"location":"05_security/","title":"Security \u2014 Auth Driven by the Spec, Not by Hand","text":"

The most distinctive thing about openapi-first security is that you never write middleware or Depends(authenticate) calls yourself. All authentication is declared in the OpenAPI document and enforced automatically.

"},{"location":"05_security/#1-where-security-lives","title":"\ud83d\uddfa\ufe0f 1. Where Security Lives","text":"

Two places in the spec, both respected:

"},{"location":"05_security/#11-componentssecurityschemes-the-inventory","title":"1.1 components.securitySchemes \u2014 the inventory","text":"
components:\n  securitySchemes:\n    internalBearer:\n      type: http\n      scheme: bearer\n      bearerFormat: JWT\n      x-server-url: \"{AUTH_SERVER_URL}\"\n      x-introspect-path: \"/introspect\"\n

x-server-url and x-introspect-path are library extensions that point at a JWT introspection endpoint (see Introspection).

"},{"location":"05_security/#12-security-per-operation-or-global-requirements","title":"1.2 security \u2014 per-operation (or global) requirements","text":"
security:\n  - internalBearer: []          # applied to every operation by default\n\npaths:\n  /pets:\n    get:\n      operationId: list_pets\n      # inherits: security: [{internalBearer: []}]\n    post:\n      operationId: create_pet\n      security: []              # override \u2014 public endpoint\n

OpenAPI dynamic-scoping rules apply: an operation-level security replaces the global list (it does not merge).

"},{"location":"05_security/#2-reading-the-spec","title":"\ud83d\udcd6 2. Reading the Spec","text":"

security.py exposes two functions:

Function Returns Purpose parse_security_schemes(spec) dict[str, dict] Collect schemes, resolve {ENV_VAR} placeholders make_security_dependencies(spec, schemes) dict[str, list[Depends]] (keyed METHOD:/path) Effective per-operation security deps

Env placeholders of the form {NAME} are resolved once at startup from os.environ. This is how you avoid embedding credentials or auth-service URLs in the committed spec.

"},{"location":"05_security/#3-the-bearer-dependency","title":"\ud83d\udd10 3. The Bearer Dependency","text":"

make_security_dependencies builds a FastAPI dependency for type: http, scheme: bearer.

Two modes, decided by whether an introspection endpoint is configured:

"},{"location":"05_security/#31-with-introspection-x-introspect-path","title":"3.1 With introspection (x-introspect-path)","text":""},{"location":"05_security/#32-without-introspection","title":"3.2 Without introspection","text":""},{"location":"05_security/#4-wiring-it-together","title":"\ud83d\udd17 4. Wiring It Together","text":"
# server-side\nfrom openapi_first.loader import load_openapi\nfrom openapi_first.security import (\n    parse_security_schemes,\n    make_security_dependencies,\n)\nfrom openapi_first.app import OpenAPIFirstApp\nimport routes\n\nspec = load_openapi(\"openapi.yaml\")\nschemes = parse_security_schemes(spec)\nsecurity_deps = make_security_dependencies(spec, schemes)\n\napp = OpenAPIFirstApp(\n    openapi_path=\"openapi.yaml\",\n    routes_module=routes,\n)\n

OpenAPIFirstApp already does this internally \u2014 the snippet above shows what it encapsulates (and what you use directly if you assemble the pieces by hand).

"},{"location":"05_security/#5-testing-security","title":"\ud83e\uddea 5. Testing Security","text":"

Because handlers are plain callables, security is the one place FastAPI's TestClient earns its keep:

from fastapi.testclient import TestClient\n\ndef test_unauthenticated_is_401(app, overrides):\n    with TestClient(app) as client:\n        r = client.get(\"/pets\")\n        assert r.status_code == 401\n\ndef test_invalid_token_using_fake_introspector(app):\n    # Point x-introspect-path at a stub uvicorn/TestServer returning active:false\n    with TestClient(app) as client:\n        r = client.get(\"/pets\", headers={\"Authorization\": \"Bearer nope\"})\n        assert r.status_code == 401\n

See Testing for the full recipe, including how tests stub the introspection server.

"},{"location":"05_security/#7-common-patterns","title":"\ud83d\udee1\ufe0f 7. Common Patterns","text":"Pattern How Public endpoint security: [] on the operation Whole-spec auth top-level security: (applies to all) Route-specific scheme replace security on that operation Env-driven auth URL x-server-url: \"{AUTH_SERVER_URL}\" Offline token carry scheme without x-introspect-path \u2192 request.state.token Auth on the client side pass the token via client.<operationId>(headers={\"Authorization\": ...})"},{"location":"05_security/#related","title":"Related","text":""},{"location":"06_error_handling/","title":"Error Handling \u2014 Fail Loud, Fail Early","text":"

openapi-first treats errors as first-class contract documents: every failure mode is a named exception with a stable import pathhare, and every one surfaces as early as possible.

"},{"location":"06_error_handling/#1-the-hierarchy","title":"\ud83e\uddec 1. The Hierarchy","text":"

All errors derive from OpenAPIFirstError (in openapi_first/errors.py), so a single except OpenAPIFirstError catches every first-party failure:

OpenAPIFirstError\n\u251c\u2500\u2500 OpenAPISpecError                     # spec-level problems\n\u2502   \u2514\u2500\u2500 OpenAPISpecLoadError             # load / parse / validation  (loader)\n\u251c\u2500\u2500 OpenAPIClientError                   # client-side contract issues (client)\n\u2514\u2500\u2500 MissingOperationHandler              # spec op with no handler     (binder)\n\n# Security / loader layers raise through OpenAPISpecError subclasses too\n
Exception Module Raised when OpenAPISpecLoadError loader Path missing, file unreadable, YAML/JSON invalid, or spec fails OpenAPI 3.x validation OpenAPIClientError client No servers, no paths, missing/duplicate operationId, missing required params at construction MissingOperationHandler errors An operation is declared whose operationId has no matching handler in routes_module"},{"location":"06_error_handling/#2-when-things-fail","title":"\u23f1\ufe0f 2. When Things Fail","text":"

The single most important rule: violations are eager, not lazy.

"},{"location":"06_error_handling/#21-at-application-startup","title":"2.1 At application startup","text":"
# openapi.yaml missing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba OpenAPISpecLoadError\n# operationId without a handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba MissingOperationHandler\n# operation with no operationId declared \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25ba MissingOperationHandler\n

Because these raise during OpenAPIFirstApp(...) construction, CI catches them the moment a spec and its routes drift \u2014 before a single request is served.

"},{"location":"06_error_handling/#22-at-client-construction","title":"2.2 At client construction","text":"
OpenAPIClient(spec)  # fails fast, same philosophy\n
"},{"location":"06_error_handling/#23-at-call-time-client","title":"2.3 At call time (client)","text":"

Runtime transport errors surface as httpx exceptions (httpx.RequestError family), not swallowed or remapped. Missing required args fail before any HTTP request is made:

client.get_user(path_params={\"user_id\": ...})     # OK\nclient.get_user()                                  # ValueError \u2014 user_id required\n
"},{"location":"06_error_handling/#3-handling-in-your-app","title":"\ud83e\uddf0 3. Handling in Your App","text":""},{"location":"06_error_handling/#31-server-side","title":"3.1 Server-side","text":"

Handlers raise FastAPI HTTPException for expected operation-level failures (404/422), and the OperationId-binding errors only exist at startup:

from fastapi import HTTPException\n\ndef get_item(item_id: int):\n    \"\"\"Retrieve an item by ID.\n\n    Implements the OpenAPI operation ``get_item``.\n\n    Args:\n        item_id (int): Identifier of the item.\n\n    Raises:\n        HTTPException: If the item does not exist (404).\n    \"\"\"\n    try:\n        return _get_item(item_id)\n    except KeyError:\n        raise HTTPException(status_code=404, detail=\"Item not found\")\n
"},{"location":"06_error_handling/#32-client-side","title":"3.2 Client-side","text":"
import httpx\n\ntry:\n    response = client.get_item(path_params={\"item_id\": 1})\nexcept httpx.HTTPStatusError as exc:\n    ...  # 4xx/5xx from the server\n

httpx.HTTPStatusError isn't raised by the library \u2014 it's the standard httpx.raise_for_status() you can opt into per call. The library never masks a response code.

"},{"location":"06_error_handling/#4-fail-fast-guarantees-recap","title":"\ud83d\udee1\ufe0f 4. Fail-Fast Guarantees Recap","text":"Layer You write The library guarantees Loader a spec path unreadable/invalid specs never reach your app Binder handler functions every operation must resolve, or the app won't start Client a spec every operationId becomes a callable; missing ones fail at construction Runtime handler code FastAPI + Pydantic handle coercion; contract checks already happened at startup

None of these can silently degrade: a violation is an exception at construction, not a 500 at request time.

"},{"location":"06_error_handling/#related","title":"Related","text":""},{"location":"07_testing/","title":"Testing \u2014 Smoke-First, Contract-First","text":"

Everything openapi-first ships is tested against real specs, real handlers, and real HTTP through FastAPI's TestClient and the bundled templates. There are no fakes of the library itself.

"},{"location":"07_testing/#1-suite-overview","title":"\ud83e\uddea 1. Suite Overview","text":"
tests/\n\u251c\u2500\u2500 conftest.py        # fixtures: spec_file, routes_module, app, client\n\u251c\u2500\u2500 test_app.py        # OpenAPIFirstApp: routes served, overrides, fail-fast\n\u251c\u2500\u2500 test_binder.py     # bind_routes: opId resolution + missing-handler failures\n\u251c\u2500\u2500 test_loader.py     # load_openapi: json/yaml, env resolution, validation\n\u2514\u2500\u2500 test_client.py     # OpenAPIClient: opId\u2192callable, params, error cases\n

Run with:

pytest            # 23 tests, zero mocks of the library\npytest -q\npytest tests/test_loader.py\n
"},{"location":"07_testing/#2-the-fixture-pattern","title":"\ud83c\udfd7\ufe0f 2. The Fixture Pattern","text":"
# conftest.py (abridged)\n@pytest.fixture\ndef spec_file(tmp_path):\n    path = tmp_path / \"openapi.json\"\n    path.write_text(json.dumps(SPEC), encoding=\"utf-8\")\n    return str(path)\n\n@pytest.fixture\ndef app(spec_file):\n    return OpenAPIFirstApp(\n        openapi_path=spec_file,\n        routes_module=routes_module(),\n    )\n\n@pytest.fixture\ndef client(spec_file):\n    return OpenAPIClient(json.loads(Path(spec_file).read_text()))\n
"},{"location":"07_testing/#3-whats-actually-asserted","title":"\ud83e\uddea 3. What's Actually Asserted","text":""},{"location":"07_testing/#31-app-level-smoke","title":"3.1 App-level smoke","text":"
def test_app_routes_served(spec_file):\n    app = OpenAPIFirstApp(openapi_path=spec_file, routes_module=routes)\n    client = TestClient(app)\n    assert client.get(\"/health\").json() == {\"status\": \"ok\"}\n
"},{"location":"07_testing/#32-fail-fast-the-heart","title":"3.2 Fail-fast (the heart)","text":"
def test_app_missing_handler_fails_at_startup(spec_file):\n    with pytest.raises(MissingOperationHandler):\n        OpenAPIFirstApp(openapi_path=spec_file, routes_module=empty_routes)\n
"},{"location":"07_testing/#33-loader-validation","title":"3.3 Loader validation","text":"
def test_loader_invalid_spec_fails():\n    with pytest.raises(OpenAPISpecLoadError):\n        load_openapi(\"broken.yaml\")\n
"},{"location":"07_testing/#34-client-contract-drift","title":"3.4 Client contract drift","text":"
def test_client_duplicate_operation_id_raises():\n    with pytest.raises(OpenAPIClientError):\n        OpenAPIClient(dup_spec)\n
"},{"location":"07_testing/#4-testing-the-templates","title":"\ud83c\udfdb\ufe0f 4. Testing the Templates","text":"

Each bundled template ships its own test + in-memory store, so you get a runnable contract test the moment you scaffold:

openapi-first scaffold crud_app my-service\ncd my-service\npytest -q\n

test_crud_app.py / test_model_app.py / test_vet_app.py exercise the full CRUD surface through TestClient \u2014 including 201/204 status codes, 404s, and (in vet_app) SSE streaming via StreamingResponse.

"},{"location":"07_testing/#5-quality-gates-ci","title":"\ud83d\udd79\ufe0f 5. Quality Gates (CI)","text":"

The same gates the library itself must pass are what keep the docs honest:

Gate Purpose black --check formatting parity ruff check lint hygiene mypy type safety (strict, --disable-error-code where intentional) pytest 23 tests, green coverage tracked via pytest-cov (HTML + XML + term)

Run the whole gate locally:

black --check openapi_first tests\nruff check openapi_first tests\nmypy openapi_first\npytest\n
"},{"location":"07_testing/#6-testing-tips","title":"\ud83d\udca1 6. Testing Tips","text":""},{"location":"07_testing/#related","title":"Related","text":""},{"location":"03_use_cases/01_quickstart/","title":"Use Case 1: Quickstart \u2014 Build Your First OpenAPI-First Service","text":"

This guide walks you from an empty directory to a running, contract-driven service in a few minutes, then talks to it with the generated client.

"},{"location":"03_use_cases/01_quickstart/#1-prerequisites","title":"\ud83d\udee0\ufe0f 1. Prerequisites","text":""},{"location":"03_use_cases/01_quickstart/#2-write-the-openapi-document","title":"\ud83d\udcc4 2. Write the OpenAPI document","text":"

OpenAPI comes first. Create openapi.yaml:

openapi: 3.0.3\ninfo:\n  title: Greeting Service\n  version: 1.0.0\nservers:\n  - url: http://localhost:8000\npaths:\n  /greet/{name}:\n    get:\n      operationId: get_greeting\n      parameters:\n        - name: name\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        \"200\":\n          description: A greeting\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  greeting:\n                    type: string\n

Key points: every operation needs operationId, and every route must exist only here.

"},{"location":"03_use_cases/01_quickstart/#3-write-the-handlers","title":"\ud83e\uddd1\u200d\ud83d\udcbb 3. Write the handlers","text":"

Create routes.py \u2014 plain functions, no decorators, named exactly like the operationIds:

# routes.py\ndef get_greeting(name: str) -> dict:\n    \"\"\"Return a greeting for the given name.\"\"\"\n    return {\"greeting\": f\"Hello, {name}!\"}\n

If a handler is missing at startup, the app refuses to boot (MissingOperationHandler) \u2014 the fail-fast guarantee catches contract drift immediately.

"},{"location":"03_use_cases/01_quickstart/#4-bootstrap-the-app","title":"\ud83d\ude80 4. Bootstrap the app","text":"

Create main.py:

# main.py\nfrom openapi_first.app import OpenAPIFirstApp\nimport routes\n\napp = OpenAPIFirstApp(\n    openapi_path=\"openapi.yaml\",\n    routes_module=routes,\n    title=\"Greeting Service\",\n)\n

Run it:

uvicorn main:app --reload\n

Visit http://localhost:8000/docs (Swagger UI) and http://localhost:8000/openapi.json \u2014 both are generated from your spec.

"},{"location":"03_use_cases/01_quickstart/#5-call-it-with-the-client","title":"\ud83d\udce1 5. Call it with the client","text":"

The same spec builds a strict client:

# client.py\nfrom openapi_first.loader import load_openapi\nfrom openapi_first.client import OpenAPIClient\n\nspec = load_openapi(\"openapi.yaml\")\nclient = OpenAPIClient(spec)\n\nresponse = client.get_greeting(path_params={\"name\": \"Ada\"})\nprint(response.status_code)   # 200\nprint(response.json())        # {\"greeting\": \"Hello, Ada!\"}\n
"},{"location":"03_use_cases/01_quickstart/#6-next-steps","title":"\ud83d\udca1 6. Next Steps","text":""},{"location":"03_use_cases/01_quickstart/#related","title":"Related","text":""},{"location":"03_use_cases/02_templates/","title":"Use Case 2: Templates \u2014 Copyable Reference Applications","text":"

openapi-first ships four runnable, copyable applications under openapi_first/templates/. They are not part of the library API \u2014 they are bundled scaffold examples you copy into your own project and build on.

"},{"location":"03_use_cases/02_templates/#1-what-templates-are","title":"\ud83c\udfac 1. What Templates Are","text":"

A template is a complete, self-contained OpenAPI-first service:

All templates share the same skeleton:

<name>_app/\n\u251c\u2500\u2500 __init__.py      # explains the template + how to scaffold it\n\u251c\u2500\u2500 openapi.yaml     # the contract (source of truth)\n\u251c\u2500\u2500 main.py          # assembles OpenAPIFirstApp from the spec\n\u251c\u2500\u2500 routes.py        # operationId-bound handler functions\n\u2514\u2500\u2500 data.py          # in-memory data store (demo only)\n
"},{"location":"03_use_cases/02_templates/#2-the-four-templates","title":"\ud83d\udccb 2. The Four Templates","text":""},{"location":"03_use_cases/02_templates/#21-health_app-minimal-liveness-probe","title":"2.1 health_app \u2014 minimal liveness probe","text":"
openapi-first scaffold health_app\n# or into a custom directory:\nopenapi-first scaffold health_app my-health-service\n
File Purpose openapi.yaml GET /health \u2192 operationId: get_health routes.py get_health() returns {\"status\": \"ok\"} main.py OpenAPIFirstApp(openapi_path=\"openapi.yaml\", routes_module=routes)

Why it exists: the absolute minimal OpenAPI-first round trip \u2014 one operation, one handler, zero moving parts. The best starting point to internalize the mental model.

Smoke test:

pip install -e .\nuvicorn main:app\ncurl http://localhost:8000/health\n# \u2192 {\"status\": \"ok\"}\n
"},{"location":"03_use_cases/02_templates/#22-crud_app-dict-based-crud","title":"2.2 crud_app \u2014 dict-based CRUD","text":"
openapi-first scaffold crud_app my-crud-service\n
File Purpose openapi.yaml Full CRUD over /items (list/get/create/update/delete) routes.py Handlers bound via operationIds list_items, get_item, create_item, update_item, delete_item data.py In-memory dict store with auto-incrementing id

Behaviors you learn:

"},{"location":"03_use_cases/02_templates/#23-model_app-pydantic-model-crud","title":"2.3 model_app \u2014 Pydantic model CRUD","text":"
openapi-first scaffold model_app my-model-service\n
File Purpose openapi.yaml Same CRUD surface, schemas reference models models.py Pydantic Item, ItemCreate, ItemBase (request/response models) routes.py Handlers type-annotated with the models; create_item sets 201 data.py In-memory store returning real model instances

Behaviors you learn:

"},{"location":"03_use_cases/02_templates/#24-vet_app-the-full-featured-demo","title":"2.4 vet_app \u2014 the full-featured demo","text":"
openapi-first scaffold vet_app my-vet-clinic\n
File Purpose openapi.yaml Five resources (parents, vets, treatments, pets, appointments) + SSE + upload + discriminated unions models.py Pydantic models incl. discriminated unions (noteType literal fields) routes.py ~20 handlers across all resources, incl. pagination, filtering, photo upload, SSE streaming sse.py Server-Sent Events helper (StreamingResponse, per-pet subscriber queues, background asyncio workers) data.py Larger in-memory store (parents \u2192 vets \u2192 treatments \u2192 pets \u2192 appointments) main.py App + CORS + lifespan example

Behaviors you learn \u2014 the advanced tier:

"},{"location":"03_use_cases/02_templates/#3-cli-reference","title":"\ud83d\ude80 3. CLI Reference","text":"
# List available templates\nopenapi-first scaffold --list\n\n# Copy a template into its default directory (template name, dashes)\nopenapi-first scaffold health_app\n\n# Copy into a custom target directory\nopenapi-first scaffold crud_app my-project/crud\n

Protip: DEFAULT_TEMPLATE is health_app, so openapi-first scaffold with no template name scaffolds the health app.

"},{"location":"03_use_cases/02_templates/#4-anatomy-of-a-scaffolded-service","title":"\ud83e\udde9 4. Anatomy of a Scaffolded Service","text":"

After openapi-first scaffold health_app my-health-service, your directory contains a drop-in FastAPI service:

my-health-service/\n\u251c\u2500\u2500 openapi.yaml   # THE contract\n\u251c\u2500\u2500 main.py        # `app = OpenAPIFirstApp(openapi_path=..., routes_module=routes)`\n\u2514\u2500\u2500 routes.py      # `def get_health(): ...`\n

Run it:

cd my-health-service\npip install -e .\nuvicorn main:app --reload\n

/docs, /openapi.json, and every declared route now exist \u2014 all derived from openapi.yaml.

"},{"location":"03_use_cases/02_templates/#5-production-disclaimer","title":"\u26a0\ufe0f 5. Production Disclaimer","text":"

Templates use in-memory, non-persistent, non-concurrency-safe data stores. They are learning scaffolds \u2014 not production references. Swap in a real data layer (SQL/REDIS/object store) the moment you go beyond a demo.

See the __init__.py of each template for detailed client examples, CLI examples, and design notes.

"},{"location":"03_use_cases/02_templates/#related","title":"Related","text":""},{"location":"03_use_cases/03_client/","title":"Use Case 3: The OperationId-Driven Client","text":"

OpenAPIClient is the other side of the contract. It reads the same OpenAPI document the server runs on and exposes one callable per operationId \u2014 so \"client\" and \"server\" are two views of one truth.

"},{"location":"03_use_cases/03_client/#1-before-you-start","title":"\ud83d\udd0d 1. Before You Start","text":"

The client is httpx-based and returns raw httpx.Response objects \u2014 no magic deserialization, no hidden schema inference:

"},{"location":"03_use_cases/03_client/#2-constructing-the-client","title":"\ud83e\uddec 2. Constructing the Client","text":"
from openapi_first.loader import load_openapi\nfrom openapi_first.client import OpenAPIClient\n\nspec = load_openapi(\"openapi.yaml\")\nclient = OpenAPIClient(spec)\n

The base URL comes from the spec's servers list (first entry) unless you pass base_url explicitly:

client = OpenAPIClient(spec, base_url=\"https://api.internal.myco/v1\")\n

You can also hand over a preconfigured httpx.Client (custom transport, TLS, retries):

import httpx\n\ntransport = httpx.HTTPTransport(retries=3)\nclient = OpenAPIClient(\n    spec,\n    client=httpx.Client(transport=transport),\n)\n
"},{"location":"03_use_cases/03_client/#3-fail-fast-at-construction","title":"\ud83d\udca5 3. Fail-Fast at Construction","text":"

OpenAPIClient(...) raises immediately if the contract is broken \u2014 you find out at startup, not on the first request:

Violation Error Spec has no servers entry OpenAPIClientError Spec has no paths OpenAPIClientError Operation missing operationId OpenAPIClientError Duplicate operationId OpenAPIClientError Operation references unknown parameters OpenAPIClientError

Missing required parameters fail at call time \u2014 pydoclint-grade strictness on the wire.

"},{"location":"03_use_cases/03_client/#4-calling-operations","title":"\ud83d\udcde 4. Calling Operations","text":"

Every operationId becomes a method. The call signature is uniform across the whole client:

response = client.<operationId>(\n    *,\n    path_params: dict | None = None,\n    query: dict | None = None,\n    headers: dict | None = None,\n    body: Any | None = None,\n    timeout: float | None = None,\n) -> httpx.Response\n

Concrete examples (from the crud_app / health_app templates):

# No parameters \u2014 simplest\nresponse = client.get_health()\nassert response.status_code == 200\n\n# Path parameter\nresponse = client.get_item(path_params={\"item_id\": 3})\n\n# Query parameters\nresponse = client.list_items(query={\"limit\": 10, \"offset\": 20})\n\n# JSON request body\nresponse = client.create_item(body={\"name\": \"Orange\", \"price\": 0.8})\n\n# Custom headers / timeout\nresponse = client.get_user(\n    path_params={\"user_id\": 1},\n    headers={\"X-Internal-Key\": \"...\"},\n    timeout=30,\n)\n

Returns: the raw httpx.Response, so status_code, .json(), .headers are all yours to inspect.

"},{"location":"03_use_cases/03_client/#5-how-parameters-are-bound","title":"\ud83e\udde0 5. How Parameters Are Bound","text":"

For each operation the client knows exactly where each parameter belongs:

OpenAPI location Client kwarg in: path path_params[name] in: query query[name] in: header headers[name] requestBody body

JSON media types are sent as json=; other media types as raw content=.

"},{"location":"03_use_cases/03_client/#6-server-client-one-spec","title":"\ud83d\udd04 6. Server \u2194 Client, One Spec","text":"
# One directory, two processes\nuvicorn main:app --port 8000                                  # server\npython -c \"import asyncio; from client_script import run; asyncio.run(run())\"  # client\n

Or the same client against a remote environment:

client = OpenAPIClient(\n    spec,\n    base_url=\"https://staging.internal.myco\",\n)\n

The URL is the only thing that changes between environments \u2014 the contract never does.

"},{"location":"03_use_cases/03_client/#7-operationid-as-the-api","title":"\u270d\ufe0f 7. OperationId as the API","text":"

Because the client is operationId-driven:

If an operationId you call doesn't exist, you get an AttributeError at construction-scan time \u2014 never a silent 404.

"},{"location":"03_use_cases/03_client/#related","title":"Related","text":""},{"location":"03_use_cases/04_codegen/","title":"Codegen \u2014 Generate Models & Routes From Your Spec","text":"

TL;DR \u2014 point openapi-first codegen at your spec and get models + routes scaffolds you can bind with one line. The codegen output is deterministic, and it's a starting point \u2014 not a maintained artifact.

"},{"location":"03_use_cases/04_codegen/#1-why-celebrate-codegen","title":"\ud83e\udded 1. Why Celebrate Codegen?","text":"

Two pain points kill OpenAPI projects:

  1. The \"write the spec, then write the same thing as Pydantic models\" step \u2014 exactly where server/client param types drift (your route says item_id: int, your client sends a string\u2026).
  2. Writing the docs/spec catalog by hand, once you have more than a handful of operations.

Codegen collapses both. One command, one source file, same generated shapes everywhere.

"},{"location":"03_use_cases/04_codegen/#2-model-generation","title":"\ud83d\ude80 2. Model Generation","text":"
openapi-first codegen models --module my_project.models --input openapi.yaml\n

The generated model module mirrors the spec's components.schemas by name:

Spec Generated components.schemas.User class User(BaseModel) components.schemas.Item class Item(BaseModel) every $ref (schema) a type: ClassVar alias \u2713 required + type from schema Pydantic Field(...) / type hints \u2713

Never hand-edit those files. If the spec changes, regenerate \u2014 just like you'd re-run cargo build after editing Cargo.toml.

"},{"location":"03_use_cases/04_codegen/#why-constructor-time-validation-still-applies","title":"Why constructor-time validation still applies","text":"

Codegen doesn't change the design: the generated models are plain Pydantic, and the client/server still validate against the spec at startup. Codegen is a convenience accelerator on top of the fail-fast guarantees in 04 \u2013 Design and 06 \u2013 Error Handling.

"},{"location":"03_use_cases/04_codegen/#3-route-generation-verification","title":"\ud83d\udd01 3. Route Generation / Verification","text":"
# dry-run verification against your routes module\nopenapi-first codegen routes --module my_routes --input openapi.yaml --check\n\n# scaffold an operation skeleton (generates the handler with a TODO)\nopenapi-first codegen routes --module my_routes --input openapi.yaml\n

Why bother? Because bind_routes (in 02 \u2013 Components) needs an operationId \u2192 handler exactly matching the spec. Codegen guarantees you never type a handler name wrong \u2014 it wears the same operationId as the spec says.

Note: codegen is build-time tooling. It does not run at runtime, and templates (the Bake-your-stuff section of 02 \u2013 Templates) make scaffolding a server out-of-the-box even simpler for greenfield projects.

"},{"location":"03_use_cases/04_codegen/#4-idempotent-output","title":"\ud83e\uddea 4. Idempotent Output","text":"

Generated output is deterministic w.r.t. the spec: - Same spec \u2192 byte-identical files (unless you hand-edit \u2014 you won't) - Ordering follows spec declaration order - No timestamps, no machine names, no hidden randomness

That determinism is what lets you git diff after a spec change and see exactly what moved.

"},{"location":"03_use_cases/04_codegen/#related","title":"\ud83e\udde9 Related","text":""}]}