OpenAPI 3.1 documents: the model, its validation and generators
README.md

nox-openapi #

OpenAPI 3.1 documents: the model, its validation and generators.

nox-openapi reads an OpenAPI 3.1
document into OCaml values, writes it back, resolves its references and
checks the rules the specification states beyond the document's JSON shape.
Generators read that model and nothing else; nox-openapi.python writes a
Python client of the API a document describes.

$ openapi validate api.json
$ openapi python api.json -o src/example --unix-socket /run/example.sock --timeout 15

The document #

Openapi.t is the OpenAPI Object, and every object the specification defines
is a record of its fields. Schemas are JSON Schema 2020-12 schemas with the
four keywords OpenAPI adds (discriminator, xml, externalDocs, example):
a type may be a list, a schema may be true or false, and a $ref may
stand beside other keywords. Every object keeps its x- extensions, in
document order, so a document decodes and encodes back with nothing dropped,
and a member the specification does not name is refused while decoding.

let document =
  Openapi.of_string_exn
    {|{"openapi": "3.1.1",
       "info": {"title": "Shapes", "version": "1"},
       "paths": {"/shapes/{shape}": {"get": {
         "operationId": "getShape",
         "parameters": [{"$ref": "#/components/parameters/Shape"}],
         "responses": {"200": {"description": "the shape"}}}}},
       "components": {"parameters": {"Shape": {
         "name": "shape", "in": "path", "required": true,
         "schema": {"type": "string"}}}}}|}

let () =
  match Openapi.operations document with
  | [ ("/shapes/{shape}", Openapi.Get, op) ] -> (
      match op.parameters with
      | Some [ p ] -> (
          match Openapi.resolve document Openapi.parameters ~at:"" p with
          | Ok (at, p) ->
              assert (at = "/components/parameters/Shape");
              assert (p.name = "shape")
          | Error _ -> assert false)
      | _ -> assert false)
  | _ -> assert false

Openapi.validate returns every broken rule as the JSON Pointer of its node
and what is wrong with it: an operationId naming two operations, a path
template and its path parameters disagreeing, two templates that differ by
their parameters' names alone, a parameter with both a schema and a
content, a reference to nothing, and the others its documentation lists.

let () = assert (Openapi.validate document = [])

Python clients #

Openapi_python.generate refuses a document Openapi.validate refuses, and
otherwise writes a Python package that calls the API:

  • _models.py: a frozen dataclass per object schema, a StrEnum per
    enumeration, an exception per RFC 9457 problem schema, and a type alias per
    oneOf. Each class has of_json, which refuses a value that does not have
    the shape the document gives it, and to_json.
  • _client.py: a Client with one method per operation, and connect.
  • _runtime.py: HTTP over a Unix socket or a TCP address, on http.client.
    The package depends on nothing outside the standard library.
  • __init__.py: everything above, by name.

The document is the only input, and the emitter decides nothing the document
does not say. A construct it does not model is refused with the JSON Pointer
of the node that holds it.

Names #

A class is named after its schema, so #/components/schemas/RefusedProblem
and RefusedProblem name one thing. An inline schema, such as an enumeration
or a nested object, is named after its owner's class followed by its member's
name in PascalCase: Band.statistics is BandStatistics.

A member, a parameter and an operation id become a Python name by one rule:
every byte outside [A-Za-z0-9_] becomes _; a word boundary (a capital
after a lower-case letter or a digit, or the last capital of a run followed by
a lower-case letter) takes a _; the result is lower-cased; a leading digit
takes a leading _, and a Python keyword a trailing one (PEP 8).

# Openapi_python.Name.python "proj:shape";;
- : string = "proj_shape"
# Openapi_python.Name.python "getOpenApiDocument";;
- : string = "get_open_api_document"
# Openapi_python.Name.python "class";;
- : string = "class_"

The wire key does not move: each attribute keeps it in its dataclasses.field
metadata, under "wire", which is what of_json reads and to_json writes.
Two members of one schema that reach one Python name are refused.

let () =
  match Openapi_python.generate document with
  | Error e -> Fmt.failwith "%a" Openapi.pp_error e
  | Ok files ->
      assert (
        List.map (fun (f : Openapi_python.file) -> f.name) files
        = [ "__init__.py"; "_models.py"; "_client.py"; "_runtime.py" ])

What is modelled #

Schemas: type object (with properties, required and
additionalProperties false, true or a schema), string (with format
date-time read as datetime.datetime), integer, number, boolean and
array; enum of strings; const; $ref to #/components/schemas; a named
oneOf of references; a named allOf of one reference and one inline object,
which is a subclass. The decoder checks required, additionalProperties: false, enum, const, minimum, maximum, exclusiveMinimum,
exclusiveMaximum, minLength, maxLength, minItems and maxItems; other
annotations, such as format other than date-time, are read as JSON Schema
2020-12 reads them, as annotations.

Operations: path and query parameters of type string or integer; a required
request body that is a $ref to an object schema, sent as JSON with its
members as the method's arguments, or binary, sent as
application/octet-stream; one 2xx answer, JSON (application/json or any
+json) or binary, or none.

Problems: every schema a response serves as application/problem+json, and
every schema it extends, is an exception. A problem detail whose type
fragment is the JSON Pointer of one of them is raised as that class, and any
other as the one they all extend.

OCaml:

  • ocaml_openapi_generator
    has the most complete typed model, of OpenAPI 3.0.3: nullable, a single
    type, boolean exclusiveMinimum, no webhooks or boolean schemas, a
    $ref that drops its sibling keywords, and extensions dropped on reading.
    It generates OCaml clients on Core, Async and jsonaf.
  • openapi and
    openapi_router build an
    OpenAPI 3.0 document from a server's routes; several objects are left as
    untyped JSON.
  • ocaml-swagger reads Swagger 2.0
    only, and the OCaml target of
    OpenAPI Generator is a Java program.

Python clients:

  • openapi-python-client
    removes a character that cannot appear in an identifier (proj:shape becomes
    projshape) and has no per-member override.
  • datamodel-code-generator
    replaces it with _ and keeps the wire key as a pydantic Field alias; it
    writes models, not a client, and needs pydantic at run time.
  • OpenAPI Generator's Python generator sanitises names the same way and takes
    per-name overrides as nameMappings in its configuration.

nox-openapi.python takes the default rule those share, keeps the wire key
the way datamodel-code-generator does but with the standard library's
dataclasses, and has no override table: a name the rule gives is the name.

License #

ISC. See LICENSE.md.

Generated client limits #

The package requires Python 3.11 or later. Named schema classes start with
an ASCII capital letter; runtime names and Python special names are refused
at their document location, rather than silently shadowing generated code.

Client and connect accept timeout and max_response_bytes. The defaults
are 30 seconds of inactivity per blocking socket operation and 16 MiB of
buffered response body before JSON decoding. None inherits the finite
default. A timeout is not a whole-call deadline. The response byte limit
bounds body buffering, not decoded Python object heap or total wire traffic.

ResponseTooLarge, a TransportError with a limit attribute, refuses an
oversized response before JSON or problem decoding. A known oversized body
is refused from the standard library's parsed framing before reading it;
an unknown-length body reads at most the limit plus one byte. Refusal closes
the response and connection without draining or retrying the request. The
next explicit call opens a fresh connection. Successful bounded responses
can reuse the connection.

The runtime source is also an installable Python project, nox-openapi-runtime,
with the nox_openapi_runtime module. From this package's root,
python3 -m pip wheel --no-deps . builds its wheel. The emitter embeds that
same source in each generated client's _runtime.py; generated clients
keep their runtime beside their models and need no installed runtime package.

The runtime's HTTP tests use Python's standard library. Run them through
Dune with a supported interpreter, for example PYTHON=python3.14 dune test -j4 ocaml-openapi/test.