Tern

openapi

Describe a web API with Tern types, and get an OpenAPI 3.1 document, Swagger UI, and a typed TypeScript client from the routes you register. Schemas come from json.schema[T](), so they always match what json.encode writes.

Compiles (not run here)
import json
import openapi
import roost

struct User:
    id: int
    name: str

struct NewUser:
    name: str

fn main():
    api = openapi.new("users", "1.0.0", "A small user service")
    openapi.bearer(&api, "an API key")
    r = roost.router()
    get_user = openapi.op("GET", "/users/{id}", "Get a user").returns[User]().tag("users")
    openapi.add(&api, &r, get_user, fn(req) roost.json(json.encode(User(req.param_int("id", 0), "ada"))))
    create = openapi.op("POST", "/users", "Create a user").accepts[NewUser]().returns[User]().status(201)
    openapi.add(&api, &r, create, fn(req) roost.json("{}"))
    openapi.serve(api, &r)          # GET /openapi.json, GET /docs
    roost.serve(r, 8080)

openapi.add registers the route on the router (like r.route(method, path, handler)) and records the operation; openapi.serve adds GET /openapi.json and GET /docs (Swagger UI, loaded from jsDelivr), so call it after the last add.

Describing an operation

openapi.op(method, path, summary) starts one; each of these returns the changed Op, so calls chain:

o.returns[T]()the response is JSON of type T
o.accepts[T]()the request body is JSON of type T
o.returns_text()the response is text/plain
o.status(code)the success status (default 200)
o.query(name, type, description)a query parameter; type is "string", "integer", "number" or "boolean"
o.describe(text), o.tag(name), o.id(operation_id)documentation; the id defaults to the method and path (getUsersId)
o.fails(code, description)a documented error response; secured operations get a 401 unless you describe your own
o.public()no credentials needed, when the spec has openapi.bearer

Path parameters come from the path: /users/{id} and /files/{*rest} both document a required string parameter.

The document and the client

import openapi
import roost

struct Item:
    sku: str
    qty: int

fn main():
    api = openapi.new("shop", "2.1.0", "")
    r = roost.router()
    o = openapi.op("GET", "/items/{sku}", "Get an item").returns[Item]().query("fresh", "boolean", "skip the cache")
    openapi.add(&api, &r, o, fn(req) roost.json("{}"))
    doc = openapi.document(api)
    print(doc.contains(`"/items/{sku}":{"get":{"operationId":"getItemsSku"`))
    print(doc.contains(`"Item":{"type":"object"`))
    ts = openapi.typescript(api)
    print(ts.contains("export type Item = { sku: string; qty: number };"))
    print(ts.contains("getItemsSku: (p: { sku: string }, q: { fresh?: boolean } = {}) => call<Item>("))
Output
true
true
true
true
  • openapi.document(spec) str: the OpenAPI 3.1 JSON. Structs become components/schemas; with openapi.bearer(&spec, description) the document declares a bearer scheme, requires it everywhere but public() operations, and lists 401 responses.
  • openapi.typescript(spec) str: export type for every schema, and createClient({ baseUrl, token, fetch, init }) with one method per operation, named by its operation id: path parameters first, then the body, then the query. Errors throw ApiError with the status and body. Enums become string unions ("Active" | "Banned") or, with payloads, tagged objects ({ Circle: number } | "Empty"); an Option is T | null. Write it to a .ts file in a build step; a web front end then calls the API with checked types.
  • openapi.server(&spec, url) lists a server URL in the document (default: /, wherever the document is served from).
  • openapi.record(&spec, o) documents an operation without registering a route, for routes added another way (a nested router with its own middleware, r.post_stream).

int becomes integer/int64 in the schema and number in TypeScript (exact up to 2^53). Enums and tuples can't be described, since they have no JSON form.