Core

OpenAPI

Generate an OpenAPI 3.1 document from registered routes and validate() schemas with generateOpenAPI(), app.openapi() and app.serveOpenAPI(), including mount prefixes, envelope responses and bearer security.

9 min readUpdated DocumentationEdit this page
On this page13

An Application can describe itself as an OpenAPI 3.1 document. The document is built from the routes that are actually registered, including mount prefixes, and from the schemas of the validate() middleware on them. There is no second description of the API to keep in sync: change a route or a schema and the document changes with it.

Note

New in 0.4.0. generateOpenAPI(), app.openapi(), app.serveOpenAPI() and app.routes() in @axiljs/core; toJSONSchema() on every validation schema.

TypeScript
TS
1import { Application, Router, generateOpenAPI } from '@axiljs/core'
2import { authenticate, JWT } from '@axiljs/auth'
3import { validate, v } from '@axiljs/validation'
4
5const app = new Application()
6const jwt = new JWT(process.env.JWT_SECRET!)
7
8const createUser = v.object({
9  name: v.string().min(2).max(100),
10  email: v.string().email(),
11  role: v.enum(['admin', 'user']).default('user')
12})
13
14const users = new Router()
15users.get('/', validate({ query: v.object({ page: v.number().integer().min(1).default(1), search: v.string().optional() }) }), listUsers)
16users.post('/', authenticate(jwt), validate({ body: createUser }), createUserHandler)
17users.get('/:id', validate({ params: v.object({ id: v.number().integer() }) }), getUser)
18app.mount('/api/users', users)
19
20// Serve the document as JSON (generated on the first request, then cached)
21app.serveOpenAPI({ title: 'Users API', version: '1.0.0', servers: [{ url: 'http://localhost:3000' }] })
Terminal
❯curl http://localhost:3000/openapi.json

From the served document, axil generate client writes a typed TypeScript client.

API

FunctionDescription
generateOpenAPI(app, options)Build the document from anything with a routes() method (an Application)
app.openapi(options)Same as generateOpenAPI(app, options)
app.serveOpenAPI(options)Register GET /openapi.json that answers with the document
app.serveOpenAPI(path, options)Same, at another path, for example '/docs/openapi.json'
app.routes()Every registered route as { method, path, middleware, handler }
excludeFromOpenAPI(handler)Mark a route handler so its route is left out of the document
isAuthMiddleware(fn)The default auth detection (see Security)

Options

OptionRequiredDescription
titleyesinfo.title
versionyesinfo.version: the version of your API, not of AxilJS
descriptionnoinfo.description
serversnoTop-level servers, for example [{ url: 'http://localhost:3000' }]
isAuthMiddlewareno(fn: Function) => boolean. Replaces the default auth detection

serveOpenAPI() throws a TypeError when the options are missing.

app.serveOpenAPI()

TypeScript
TS
app.serveOpenAPI({ title: 'Users API', version: '1.0.0' })                          // GET /openapi.json
app.serveOpenAPI('/docs/openapi.json', { title: 'Users API', version: '1.0.0' })    // GET /docs/openapi.json
  • The route is registered on the application like any other app.get() route, so config.prefix applies to it.
  • The document is generated on the first request and cached for the life of the process. Register your routes before the first request reaches the endpoint; routes added later are not included.
  • The serveOpenAPI() route itself is left out of the document.

app.routes()

Returns every route in matching order: the application's own routes first, then each mounted router's routes, in mount order.

FieldDescription
method'GET', 'POST', … or '*' for routes registered with all()
pathThe URL a client requests, with :params and * wildcards
middlewareGlobal, router and route middleware, in the order they run (error handlers excluded)
handlerThe final route handler

How path is built:

  • Application routes include config.prefix.
  • Mounted routes get the mount prefix plus the router's own prefix. The application prefix does not apply to mounted routers, as at runtime.
  • A router created with the mount prefix already in it (new Router('/users') mounted at /users) is reported without doubling the prefix.
  • A method and path that an earlier source already serves is reported once, as the runtime matches it once.

router.routes() gives the same information for a single router.

TypeScript
TS
app.routes().map(r => `${r.method} ${r.path}`)
// ['GET /openapi.json', 'GET /api/users', 'POST /api/users', 'GET /api/users/:id']

excludeFromOpenAPI(handler)

Returns the handler, marked with Symbol.for('axiljs.openapi.exclude') (exported as OPENAPI_EXCLUDE). Use it for internal or operational routes that should not appear in the public contract:

TypeScript
TS
import { excludeFromOpenAPI } from '@axiljs/core'

app.get('/internal/metrics', excludeFromOpenAPI(metricsHandler))

Document shape

The shape is stable, so client generators can rely on it.

ItemRule
Versionopenapi: '3.1.0', jsonSchemaDialect JSON Schema 2020-12 (OPENAPI_VERSION, OPENAPI_SCHEMA_DIALECT)
Paths:id becomes {id}. Routes of one shape (/users/:id, /users/:userId) share the parameter names of the first one, because OpenAPI treats them as the same path
Path parametersAlways required. Schema from the params schema, otherwise { type: 'string' }
Query parametersOne query parameter per property of the query schema, required according to its required list
Request bodyapplication/json, stored as components.schemas.<OperationId>Body and referenced with $ref. Required unless the body schema accepts a missing body
Success response201 (Created) for POST, 200 otherwise; HEAD has no content. Body: components.schemas.Envelope
Error responsescomponents.responses.Error for 422 (routes with validation), 401 and 403 (routes with auth), 404 (routes with path parameters), and always 4XX and 5XX
Securitysecurity: [{ bearerAuth: [] }] on routes with auth middleware. components.securitySchemes.bearerAuth (HTTP bearer, JWT) is only added when at least one route uses it
SkippedRoutes registered with all(), wildcard (*) routes, the serveOpenAPI() route and handlers wrapped in excludeFromOpenAPI()

operationId

The lower-case method followed by the path segments in PascalCase; a :param segment becomes By<Param>:

RouteoperationId
GET /getRoot
GET /api/usersgetApiUsers
POST /api/userspostApiUsers
GET /api/users/:idgetApiUsersById

When two routes produce the same id, a numeric suffix (2, 3, …) keeps them unique.

Envelope and errors

Every success response references the AxilJS response envelope:

JSON
JSON
1{
2  "Envelope": {
3    "type": "object",
4    "properties": {
5      "status": { "type": "integer", "description": "HTTP status code" },
6      "code": { "type": "string", "description": "Status name, e.g. 'HTTP_200_OK'" },
7      "message": { "type": "string" },
8      "data": { "description": "Response payload (handler-specific, not described)." }
9    },
10    "required": ["status", "code", "message", "data"]
11  }
12}

data is unconstrained, because the output of a handler cannot be introspected. Error responses reference ErrorResponse, the body the default error handler writes: { error: { code, message } }, plus stack outside production.

Example

For the application at the top of this page, the POST /api/users operation is:

JSON
JSON
1{
2  "operationId": "postApiUsers",
3  "responses": {
4    "201": {
5      "description": "Created",
6      "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } }
7    },
8    "401": { "$ref": "#/components/responses/Error" },
9    "403": { "$ref": "#/components/responses/Error" },
10    "422": { "$ref": "#/components/responses/Error" },
11    "4XX": { "$ref": "#/components/responses/Error" },
12    "5XX": { "$ref": "#/components/responses/Error" }
13  },
14  "requestBody": {
15    "required": true,
16    "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PostApiUsersBody" } } }
17  },
18  "security": [{ "bearerAuth": [] }]
19}

and its body schema in components.schemas is the JSON Schema of createUser:

JSON
JSON
1{
2  "PostApiUsersBody": {
3    "type": "object",
4    "properties": {
5      "name": { "type": "string", "minLength": 2, "maxLength": 100 },
6      "email": { "type": "string", "format": "email" },
7      "role": { "type": "string", "enum": ["admin", "user"], "default": "user" }
8    },
9    "required": ["name", "email"]
10  }
11}

GET /api/users gets two optional query parameters, page ({ type: 'integer', minimum: 1, default: 1 }) and search ({ type: 'string' }), and GET /api/users/{id} a required path parameter id of type integer.

How validate() schemas are used

Schema discovery is duck-typed, so @axiljs/core does not depend on @axiljs/validation:

  1. A middleware in the route's chain that carries fn[Symbol.for('axiljs.validation.schemas')] or fn.schemas, shaped { body?, params?, query? }, provides schemas. The middleware returned by validate() has both.
  2. Each schema is converted with its toJSONSchema() method. A plain JSON Schema object is used as it is.
  3. When several validation middleware run on one route, the later one wins per location.
validate() locationBecomes
paramsThe schema of each path parameter, by property name
queryOne query parameter per property
bodyThe request body component

A route with any validation schema also gets the 422 error response.

Security

A route gets the bearer security requirement, and the 401 and 403 responses, when a middleware in its chain counts as authentication. The default check, isAuthMiddleware(fn), accepts:

  • a function with fn[Symbol.for('axiljs.auth')] set (exported as AUTH_MIDDLEWARE). Since 0.4.0 the middleware returned by authenticate(), requireRole(), requirePermission() and requireOwnership() from @axiljs/auth carries this marker;
  • as a heuristic, a function whose name contains authenticate, requireAuth, requireRole, requirePermission or requireOwnership.

Your own auth middleware can set the marker, or you can pass your own predicate:

TypeScript
TS
1import { AUTH_MIDDLEWARE } from '@axiljs/core'
2
3const requireApiKey: MiddlewareFn = (req, res, next) => { /* ... */ }
4;(requireApiKey as any)[AUTH_MIDDLEWARE] = true
5
6app.openapi({ title: 'API', version: '1.0.0', isAuthMiddleware: fn => fn === requireApiKey })

Note

The middleware list includes global middleware. An auth middleware registered with app.use() therefore marks every route as protected.

Limitations

  • Response payloads (data) are not described, since handler output cannot be introspected.
  • Handlers that answer with res.json() instead of the envelope helpers are still documented with the envelope, and every POST is documented with 201.
  • custom() and transform() rules of validation schemas are not represented.
  • Any middleware that counts as authentication marks the route, including authenticate(jwt, { required: false }).
  • The served document is cached after the first request, so routes added later are not included.
  • Routes registered with all() and wildcard routes have no OpenAPI operation.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY