Tern

Clients from OpenAPI specs

Many services publish an OpenAPI 3.x document describing their HTTP API (Stripe, GitHub, Slack, Twilio, OpenAI...). tools/openapi_client.tn turns one into a typed Tern package: a Client, one function per operation, and a struct per schema, over roost's HTTP client (tern openapi-client runs tools/openapi_client.tn).

tern openapi-client SPEC.json -o OUTDIR --name NAME [--tag TAG ...]

It writes OUTDIR/NAME.tn, a package of one module, and OUTDIR/README.md. Put NAME.tn next to your program (or in deps/NAME/) and import NAME. The comment at the top of NAME.tn lists every public function with its signature, one per line: read that first.

--tag (repeatable, or --tag a,b) keeps only the operations with one of those tags, and only the schemas they use. Big specs build faster that way: all of GitHub's API is 43,000 lines and takes ~40 s to compile; its issues and users tags are 4,000.

Using a generated client

import github
import os

fn main():
    c = github.client("", os.env("GITHUB_TOKEN", ""))    # "" base URL: the spec's server
    r = c.repos_get("golang", "go")                       # Result[github.FullRepository, github.Error]
    if r is Ok(repo):
        print(repo.full_name, repo.stargazers_count)
    if r is Err(e):
        print(e.status, e.message)                        # 0 when no response came
    repos = c.repos_list_for_user("octocat", None, None, None, Some(10), None).unwrap_or([])
  • NAME.client(base_url, token) sends the token the way the spec's security scheme says (bearer, an API key header or query parameter, or basic auth with "user:password"). with_bearer, with_api_key, with_query_key, with_basic, with_header and with_timeout return a changed copy. Every client sends a User-Agent (GitHub requires one).
  • Operations are named from operationId in snake_case (repos/list-for-user becomes repos_list_for_user), or from the method and path when there is none. Arguments: path parameters, then required query and header parameters, then optional ones as Option[T], then body.
  • The result is Result[T, NAME.Error]: T is the 2xx JSON response decoded, int (the status) when the response has no body, str when it isn't JSON. Error has status, body, and message (the API's own message when the body has one).
  • Request structs have a constructor taking the required fields (stripe.new_post_customers_body()); set optional ones afterwards: b.email = Some("a@example.com"). None fields are left out of the request.

How schemas become types

SchemaTern type
object with properties (also through allOf)a struct; component schemas keep their names (full-repository is FullRepository), inline ones are named after where they appear (PostCustomersBodyAddress)
string, integer, number, booleanstr, int, float, bool
array[T]
object with only additionalProperties{str: T}
optional or nullable (nullable: true, type: [T, "null"], anyOf: [T, null])Option[T]
string enumstr, with the values in a comment
oneOf / anyOf of different shapes, free-form objectsstr holding the raw JSON (commented "raw JSON")

A oneOf/anyOf alternative that only allows "" (Stripe's way of clearing a field) is ignored. JSON keys that aren't Tern names are renamed (photoUrls is photo_urls, +1 is plus_1, in is in_, _links is links), with the JSON key in a comment; the generated decoders and encoders map them. Decoding is lenient: a missing or mistyped field gets its zero value (or None) rather than failing the call. A struct that would contain itself other than through an array, map or Option gets an Option at the point of the cycle.

Request bodies are JSON, or form-encoded when the operation only takes application/x-www-form-urlencoded (nested values as a[b][0]=c, as Stripe expects). A raw JSON object passed as a query parameter is sent the same way (created[gt]=100). Operations whose only body is multipart/form-data are skipped and listed at the top of the module. Cookie parameters are ignored.