Skip to content
v0.5 isn't released yet: these pages follow the main branch. To try it, install the release candidate, v0.5.0-rc.1.
OpenAPI reference

OpenAPI reference

Package web/openapi and what it writes. How to use it: Describe an API with OpenAPI.

API

NameDoes
openapi.Spec(r, cfg)The OpenAPI 3.1.0 document of r’s typed routes, as indented JSON (the same routes and Config give the same bytes), and warnings about what it left out or couldn’t describe
openapi.Check(r, cfg)An error unless cfg.File holds Spec’s document (Windows line ends allowed); the error names the first line that differs and says to run go run . openapi. Also an error when a route under cfg.Prefix is one the document leaves out (not a typed handler, or every method)
openapi.Register(app, srv, cfg)Adds the openapi command, and serves the document at cfg.Path if set (built on the first request). Call it after adding the routes. An error without cfg.Title
web.Documented(h, web.MiddlewareDoc{…})The handler a middleware returns, with what the middleware asks for and may answer (Security, Scopes, Responses), which the routes it wraps report; Name and Detail name it in route:list --json
web.RouteInfo.Input, .Output, .StatusA typed route’s input and result types and its Status (0 unless set)
web.RouteInfo.HandlerA typed route’s function, without its package path: handlers.Bookmarks.Index
web.RouteInfo.MiddlewareA MiddlewareDoc for each of the route’s middleware, outermost first (read-only): its Name (the function that makes it, as Go code names it, unless Documented gives one) and, for the documented ones, what they said
r.GlobalMiddleware()The same for the router’s global middleware (UseGlobal)
auth.RequireAbilities(abilities…)Middleware: a token needs the abilities (403), a guest is refused (401, WWW-Authenticate: Bearer); documents them as the bearer token’s scopes. Put it after Require

Config

FieldDefaultMeaning
Title(required)info.title
Version1.0.0info.version: the API’s version, not Anetos’s
Descriptioninfo.description, Markdown
Prefixevery typed routeOnly the routes at or below this path (a trailing / is ignored)
Fileopenapi.jsonWhere the command writes and Check reads, relative to the working directory
Pathnot servedThe route serving the document; it isn’t described in it
Servers/servers’ URLs
SecuritySchemesbearer onlySchemes middleware may name: openapi.SecurityScheme{Type, Scheme, BearerFormat, In, Name, Description}, Type http or apiKey

The command

openapi [--check] [--out=FILE], added by openapi.Register.

FlagDefaultMeaning
--outConfig.FileThe file to write or check; - writes to the standard output
--checkfalseExit 1 if the file isn’t the document of the routes, instead of writing it

It prints a warning per route it leaves out or can’t fully describe. It doesn’t boot the app, so it needs no database.

Operations

WhatFrom
Which routesTyped routes (web.H, registered as it returns them) at or below Prefix; other routes and any-method routes are left out with a warning
operationIdThe route’s name; else the handler’s (Bookmarks.Index, a function’s welcome); else the method and path. Unique (a number is added)
tagsThe handler’s receiver type (Bookmarks); none for functions
parametersThe path’s wildcards ({path...} is {path}), then the input’s query and header fields
requestBodyThe input’s other fields as application/json, or multipart/form-data (the fields a form binds, by their form names, and the files) when it has files; none for GET and HEAD. Required when a field is
SuccessThe route’s Status (200 by default) with the result’s schema; web.Empty, 204 and 205 without content; a web.Responder result: 2XX without content, with a warning
Errors400 (InvalidValues) when there are values to bind; 422 (InvalidInput) with validate rules or a Validate method; each documented middleware’s statuses; default (Error). All application/problem+json, the Problem schema
securityThe documented middleware’s schemes, with their scopes merged; [] on the others when some operations have any

Two routes OpenAPI can’t tell apart (GET /a/{id} and DELETE /a/{key}; one method and path on two hosts) are an error.

Schemas

Types are described as encoding/json writes (results) and reads (bodies) them: names from json tags, embedded structs’ fields promoted, json:",string" numbers as strings.

GoSchema
string, boolstring, boolean
int, int8, int16 / int32, int64integer / with format int32, int64
unsigned integersinteger, minimum 0
float32, float64number, format float, double
time.Time, anetos.Datestring, format date-time, date; in a body, an optional anetos.Date (not a pointer) is anyOf that and an empty string, which binds as no date
[]bytestring, contentEncoding base64
*multipart.FileHeaderstring, format binary
time.Duration parameterstring (30s, as the binding reads it); in a body, an integer (nanoseconds)
slices, arraysarray with items
mapsobject with additionalProperties
a pointerits type, nullable (["string", "null"]; anyOf a $ref and null)
a named structa component, $ref: "#/components/schemas/Name"
an anonymous structan inline object
an encoding.TextMarshalerstring
an interface, json.RawMessage, a json.Marshalerany value ({}); a json.Marshaler with a warning
In a resultIn a body
Every field without omitempty or omitzero is required, except those promoted through an embedded pointerrequired comes from the validate rule
Slices and maps aren’t nullable: answer empty ones, not nilpath, query and header fields aren’t in the body

Components’ names: the Go type’s (BookmarkResponse); a generic type’s with its type arguments’ names (db.Page[BookmarkResponse] is PageBookmarkResponse); the package’s name first when two types share a name (handlers.Order); …Input for a type’s body schema when it’s a result too; a number after a name still taken. Problem is the problem details'.

Validation rules

What a validate tag says that JSON Schema can, in bodies and parameters:

RuleSchema
requiredrequired; a string minLength 1, an array minItems 1, a map minProperties 1; in a non-pointer field, a number not: {const: 0}, a bool const: true
min, max, size, betweenminLength/maxLength (strings), minimum/maximum (numbers), minItems/maxItems (slices), minProperties/maxProperties (maps)
inenum (with null for a pointer)
email, url, uuid, date, datetime, ipv4, ipv6format email, uri, uuid, date, date-time, ipv4, ipv6; url also a pattern of its schemes (http and https unless it names others), as uri allows any
distinctuniqueItems
others (unique, confirmed, after, custom rules…)not shown; still checked

A field that isn’t required may be blank whatever its other rules (as validate skips them): its schema is anyOf the constrained schema and a blank one ({"type": "string", "pattern": "^\\s*$"}, an empty array or map).

Middleware

MiddlewareDocuments
auth.Auth.Requirebearer; 401
auth.Auth.TokenMiddleware401 (a bad token)
auth.RequireAbilities(abilities…)bearer with the abilities as scopes; 401, 403
rbac.Require, rbac.RequireIn401, 403
ratelimit.Middleware429
your ownweb.Documented(h, web.MiddlewareDoc{Security, Scopes, Responses})

Global middleware (UseGlobal) isn’t seen.

Warnings

WarningMeans
not a typed handler (web.H, registered as web.H returns it): left outA plain handler, or web.H’s handler wrapped in another function
a route for every method isn't describedHandle("", …)
its result is a web.Responder…: described as any 2XXThe handler chooses its status and body as it runs
its result is an interface…: described as any valueany or another interface type
… has its own MarshalJSON: described as any valueThe type writes its own JSON
… can't be written in JSONA channel, a function…