Skip to content

OpenAPI

nilo builds an OpenAPI 3.1 document from your handler signatures, so the document cannot drift from what the server actually does.

Reference: OpenAPI options, the document without a server, handler returns · Design: OpenAPI

Serving the document

You already wrote the contract. One line serves it:

app.docs(.{ .title = "Orders", .version = "2.1.0" });

That gives you an OpenAPI 3.1 document at /openapi.json, and a page for reading it at /docs. Both are built when listen() runs, so it does not matter whether this line comes before or after your routes.

What the document is built from

Nothing is annotated, because there is nothing to keep in step. fn getUser(db: *Db, id: u32) !User is read by exactly the same compile-time pass that decides what to pass to the handler:

"/users/{id}": { "get": {
  "operationId": "getUsersId",
  "parameters": [{"name":"id","in":"path","required":true,"schema":{"type":"integer"}}],
  "responses": {"200": {"content": {"application/json": {"schema": … User … }}}}
}}
In the signature In the document
a path param a path parameter, typed, required
Query(T) one query parameter per field; a field with a default, or a ?T, is not required
a struct argument the request body schema; a field with a default, or a ?T, is not required
a returned struct the response schema; every field is required, because the writer always sends it (a ?T that is empty goes out as null), so a generated client does not null-check one. A type that is both read from a body and returned is two components when the two disagree about a field (see Named schemas)
an enum the list of its names
an optional field a nullable property
!T the 200 response schema
!?T the 200 schema and a 404
!Status(201, T) a "201" response, named
!Response(T) default, because the status is picked at runtime
a *Ctx and no return value default, because nilo cannot tell whether the handler wrote a response of its own
anything nilo can reject before the handler runs a 400

Operation names (operationId)

Each operation's operationId is derived from the method and path, and a route can set its own with app.named. The derived name (getUsersId above) is a good default and a poor key: nobody chose it, and it changes when the route's path changes. If something on your side depends on it, give the route its own name:

try app.named("addPartnerCapability")
    .put("/partners/:id/capabilities/:capability", addCapability);

This works with groups and with with, and two routes with the same name stop the process at registration (ADR 119). It sets only what the route is called: everything else in the document still comes from the signature, which is the point of this whole page. A name may contain letters, digits, _ and -, and must start with a letter or _. A port whose contract was generated by somebody else's tool may contain auth-login, and every client generator handles that (ADR 119).

The same name is available on the request. c.routeName() is the operationId of the route that matched, whether you set it or it was derived as getUsersId. That lets one middleware keep an authorisation table keyed by it for every route, and reject a route the table forgot instead of letting it through (the middleware page).

Named schemas (components/schemas)

A struct type with a name is written once under components/schemas and referenced everywhere else:

"components": {"schemas": {
  "Todo": {"type":"object","properties":{"id":{"type":"integer"}, …}},
  "Failure": {"type":"object","properties":{"error":{"type":"string"},"status":{"type":"integer"}}}
}}

so a route says {"$ref":"#/components/schemas/Todo"} instead of carrying a copy. Generated clients get one Todo type instead of five identical ones.

A type that is both read from a body and returned is two components when its two halves differ. A request marks a field with a default, or a ?T, as not required; a response marks every field it always sends as required. Where that makes the two shapes different, the response keeps the plain name and the request is the name with Input after it, User and UserInput, each referred to from where it is used, and a struct holding such a type is split the same way. Where the two halves agree there is one component, as before, and a type only ever read keeps its plain name. If another type is already called UserInput, neither takes the name and both are written under their full names.

Failure is the shape every error body takes (ADR 024). It is nilo's own shape, or the struct you named with app.failures(T), read from its fields and written under the name Failure, not again under the type's own name.

An instantiated generic also gets a name, built from the name the compiler gives it:

Zig in the document
Page(Order) Page_Order
Addressed(Str) Addressed_Str
Addressed([]const u8) Addressed_Text

This matters more than it looks. A generic is how Zig says "the same shape twice", and that is exactly what a request struct and a response struct are: one holding Str, one holding []const u8 (ADR 003). Writing them as Addressed(Text) instead of two separate structs should not cost the shape its name in every generated client.

An anonymous struct has no name worth putting in anybody's client, so it is written out in place. Two types that share a short name (an a.User and a b.User) both keep their full names, because a generator given one User that means two shapes produces code that does not compile. Where two generics render to the same name but are not the same shape, neither gets the name and both are written out in place. There is no limit on how many shapes a document names: there used to be one, at sixty-four, and a product with six contexts reached it (ADR 170).

Describing session authentication (app.guard)

Declare the session middleware with app.guard, or the document describes every route behind it as open. A handler that takes nilo.Authorization(.bearer) gets a security entry automatically, because the header is in its type. A session cookie is not in any type (the middleware in front of the group reads it), so the document cannot see it until you say so. Saying so is one line:

const api = app.group("/api");
try api.use(requireSession);
try app.guard(requireSession, nilo.session.host_cookie_name);

try api.get("/me", me);                            // cookieAuth, and a 401
try api.without(requireSession).post("/sign-in", signIn);   // open, as it is

Every route that requireSession sits in front of (through use, useOn or with, minus what without removed) is written with a cookieAuth requirement and a 401. components.securitySchemes gains {"type":"apiKey","in":"cookie","name":"__Host-session"}, which a generated client reads as "send the cookie". Which routes those are is read from the middleware wiring when the document is written, not from the declaration, so moving a without updates the document with no other change. The only things nilo takes on trust are the cookie's name and that the middleware rejects requests without it (ADR 153).

A route behind the guard whose handler also asks for Authorization is written with both schemes in one requirement, meaning both are needed: the guard ran first, and the handler still asked.

There is one guard per App, because a program has one session cookie. Declaring it installs nothing, so still use the middleware as before.

What the document does not describe

The document never claims anything your signature does not state.

Statuses. A handler returning Response(T) picks its status at runtime, so the document says default instead of guessing 200. Status(code, T) puts the code in the type, and then the document names it.

Failures. The only failure a signature can state is "this might not be there", which is !?T and becomes a 404. A fail.conflict(…) inside a handler is invisible here, on purpose: a compile-time check cannot read a function body, and an annotation saying otherwise would be a second thing to keep in step with the code, which is what this whole feature exists to avoid (ADR 023).

Shapes. A type with no JSON shape is {}, meaning "anything", which is true. An untagged union is such a type: nothing in the type says which variant is active. A union(enum) is not, and gets a oneOf matching the encoding it actually sends: the one std.json writes by default or, if the type carries nilo_json, a discriminated one with discriminator and each variant pinned to its own tag value (JSON shapes).

Unknown keys. A struct that says .unknown_fields = .ignore is additionalProperties: true. Every other struct says nothing about it, not false: a request refuses an unknown key, but the same schema describes a response, and a client reads a response ignoring the keys it does not know (ADR 168).

Str and Text versions of one type

Meta(Str) for the request body and Meta(Text) for the database row become one component called Meta. This is the split nilo asks for, and it used to cost a generated client two identical types. It no longer does: where a _Str and a _Text version render the same all the way down, they are one component (ADR 016). Two shapes that only look alike, such as Page_Order and Page_User, keep their own names.

Types with a custom jsonStringify

If your type has a jsonStringify, describe what it writes with nilo_openapi. std.json calls jsonStringify and never looks at your fields, so nilo does not either. Describing the struct's fields would describe something the server does not send, which is worse than saying nothing. It broke every generated client that read a nilo_id value, because a Uuid is sent as 36 characters while its struct is sixteen bytes (ADR 016).

So say what you send, beside the function that sends it:

const Uuid = struct {
    bytes: [16]u8,

    pub fn jsonStringify(self: Uuid, jw: anytype) !void {
        try jw.write(&self.toText());
    }

    pub const nilo_openapi = .{ .type = "string", .format = "uuid" };
};

type is required and is one of "string", "integer", "number" or "boolean". format is optional and is a hint to a client generator: "uuid", "date-time", "email". Those two fields are all there is. This is a way for a custom writer to stop being described wrongly, not a second language for describing types.

nilo's own types already do this: nilo_id's Uuid, and nilo_sql's Timestamp, Decimal, Interval and Inet. You need it only for a type of your own that writes itself.

A custom writer with no nilo_openapi gets {} and a note saying the writer is custom and how to describe it. The document stays visibly silent rather than confidently wrong.

Types with a custom parser (nilo_parse)

A type with nilo_parse and a nilo_openapi is described as what nilo_openapi says, whether or not it also writes its own JSON. For example, an sql.Ordering is read from ?order=due:desc and described as {"type":"string"}, not as the struct of terms it holds (ADR 166). A nilo_expects beside it ("a ticket number like T-1234") is what every 400 for that field asks for, instead of the type's name.

Number ranges

An integer states the range of its type: a u8 is {"type":"integer","minimum":0,"maximum":255} and an i8 is -128 to 127, because the server refuses anything outside it with a 400, so the document can promise it. A u128 states no maximum, since its top does not fit the number the document is written with. nilo.Within(1, 200) states both ends, {"type":"integer","minimum":1,"maximum":200}, read from the type that enforces the range, so a generated client rejects 500 before sending it (ADR 167):

const ListQuery = struct {
    limit: nilo.Within(1, 200) = .of(50),
    offset: u32 = 0,
};

minimum and maximum are deliberately not keys of nilo_openapi. A marker is only a claim, and a range the document promises must be one the type enforces.

Text length and format

Text types describe their limits the same way (ADR 193). nilo.Text(.{ .min = 10, .max = 72 }) is described as {"type":"string","minLength":10,"maxLength":72}, nilo.Email as {"type":"string","maxLength":254,"format":"email"}, and nilo.Url as format: uri, each read from a type that rejects what does not fit. A check of your own, and a nilo_check on the struct, have no JSON Schema equivalent and are not described: the field is a string, and the 422 response is where those rules are reported.

Non-JSON response types

A type that writes its own response body is described with its own content type. A type carrying nilo_content_type and nilo_write responds with whatever bytes it writes, under its own content type (Responses), and the document says so. The response's content key is the type's own application/xml or text/csv instead of application/json. The schema under it is whatever the type declares with nilo_openapi, or {} with a note (this type reads or writes its own bytes, and has not said what they look like) when it declares nothing. nilo cannot read a schema from a function that writes XML, and does not try (ADR 157).

A protobuf message is filed under both its spellings, and a type that reads its own body under its label. A struct with a wire table, as a body or an answer, appears under application/json and application/proto with one schema, its fields, since the request's content type decides which it is (Requests). A body type with nilo_decode appears under its own nilo_content_type, described the way a type that writes its own body is (ADR 256).

A type alias does not create a new name. pub const NewDoc = Filing(Str); reads well in Zig, but the document still calls the shape Filing_Str: the name comes from the compiler's name for the instantiation, and a Zig alias does not create a new one. Write the struct out in full if the client's type name matters.

Handlers that write their own response

A handler that takes a *Ctx and returns nothing is described as default, because its signature cannot say what it sends. It may have sent a response itself somewhere in its body, and no reading of its signature can find out whether it did. The document says exactly that:

"responses": {"default": {"description": "this endpoint holds the Ctx and returns
                                          nothing, so it may write its own response
                                          — its signature does not settle what it
                                          answers"}}

and listen() reports how many such handlers there are, once, at startup:

info: 1 of 12 routes hold the Ctx and return nothing, so the API description
      cannot say what they answer — a handler that means "200, empty" says so by
      returning `Status(200, void)` (ADR 120)

Taking a *Ctx is not what causes this: a handler that reads a header and then returns its response is described like any other. Returning nothing while holding one is.

The count covers your routes, not nilo's. app.health(path) and app.metrics(opts) register handlers of that kind, and both are described: the health page as a 200 of {"status":…}, and the metrics page as a 200 under the Prometheus text content type. Neither is counted in the line above, so a program with a health page whose own handlers are all described prints no line at all (ADR 120).

A handler that really means "200, empty" should say so by returning Status(200, void). The document then includes the 200 instead of default. nilo cannot tell the two cases apart from the signature, which is why the wording hedges instead of guessing (ADR 120).

That is the trade the whole feature rests on: a document that promises too little is still useful, and one that guesses is worse than none (ADR 016).

Authentication that lives only in middleware is not visible in any signature, so it is not described unless you declare it with app.guard. That is a known gap rather than a decision.

Options

title default "API"
version default "1.0.0"
description
path where the document is served. Default /openapi.json
ui_path where the reading page is served. Default /docs; empty for none

The /docs page loads its viewer from a CDN, so set .ui_path = "" on a server with no outbound network. The document itself never needs one.

What it costs

Nothing on the request path. The document is served from memory like a static file, so it has an ETag and a repeat visit gets a 304.

It does cost binary size, unconditionally: +14 KB on the hello example and +34 KB on rest, whether or not docs() is ever called. The linker cannot see that nobody wants it. Making that conditional would need a build option that every dependent passes through, which does not exist yet.