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.
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.
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' }] })From the served document, axil generate client writes a typed TypeScript client.
API
| Function | Description |
|---|---|
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
| Option | Required | Description |
|---|---|---|
title | yes | info.title |
version | yes | info.version: the version of your API, not of AxilJS |
description | no | info.description |
servers | no | Top-level servers, for example [{ url: 'http://localhost:3000' }] |
isAuthMiddleware | no | (fn: Function) => boolean. Replaces the default auth detection |
serveOpenAPI() throws a TypeError when the options are missing.
app.serveOpenAPI()
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, soconfig.prefixapplies 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.
| Field | Description |
|---|---|
method | 'GET', 'POST', … or '*' for routes registered with all() |
path | The URL a client requests, with :params and * wildcards |
middleware | Global, router and route middleware, in the order they run (error handlers excluded) |
handler | The 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.
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:
import { excludeFromOpenAPI } from '@axiljs/core'
app.get('/internal/metrics', excludeFromOpenAPI(metricsHandler))Document shape
The shape is stable, so client generators can rely on it.
| Item | Rule |
|---|---|
| Version | openapi: '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 parameters | Always required. Schema from the params schema, otherwise { type: 'string' } |
| Query parameters | One query parameter per property of the query schema, required according to its required list |
| Request body | application/json, stored as components.schemas.<OperationId>Body and referenced with $ref. Required unless the body schema accepts a missing body |
| Success response | 201 (Created) for POST, 200 otherwise; HEAD has no content. Body: components.schemas.Envelope |
| Error responses | components.responses.Error for 422 (routes with validation), 401 and 403 (routes with auth), 404 (routes with path parameters), and always 4XX and 5XX |
| Security | security: [{ bearerAuth: [] }] on routes with auth middleware. components.securitySchemes.bearerAuth (HTTP bearer, JWT) is only added when at least one route uses it |
| Skipped | Routes 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>:
| Route | operationId |
|---|---|
GET / | getRoot |
GET /api/users | getApiUsers |
POST /api/users | postApiUsers |
GET /api/users/:id | getApiUsersById |
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:
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:
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:
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:
- A middleware in the route's chain that carries
fn[Symbol.for('axiljs.validation.schemas')]orfn.schemas, shaped{ body?, params?, query? }, provides schemas. The middleware returned byvalidate()has both. - Each schema is converted with its
toJSONSchema()method. A plain JSON Schema object is used as it is. - When several validation middleware run on one route, the later one wins per location.
validate() location | Becomes |
|---|---|
params | The schema of each path parameter, by property name |
query | One query parameter per property |
body | The 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 asAUTH_MIDDLEWARE). Since 0.4.0 the middleware returned byauthenticate(),requireRole(),requirePermission()andrequireOwnership()from@axiljs/authcarries this marker; - as a heuristic, a function whose name contains
authenticate,requireAuth,requireRole,requirePermissionorrequireOwnership.
Your own auth middleware can set the marker, or you can pass your own predicate:
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 with201. custom()andtransform()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.
Related
- JSON Schema: how validation schemas convert
- Generate a typed client:
axil generate client - Routing: routers and
app.mount() - Auth middleware: the
AUTH_MIDDLEWAREmarker
Was this page helpful?