OpenAPI
Generate an OpenAPI 3.1 document from the same specs you mount.
import { writeFileSync } from 'node:fs';
import { generateOpenApiDocument } from 'hono-bento/openapi';
import { specs } from './specs';
const document = generateOpenApiDocument(specs, {
info: { title: 'Todos API', version: '1.0.0' },
servers: [{ url: 'https://api.example.com' }],
securitySchemes: {
bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
apiKeyAuth: { type: 'apiKey', in: 'header', name: 'X-Api-Key' },
},
// Which scheme each strategy implements, so each route lists only the ones it accepts.
securityByStrategy: { jwt: 'bearerAuth', apiKey: 'apiKeyAuth' },
});
writeFileSync('openapi.json', `${JSON.stringify(document, null, 2)}\n`);Commit the output and check it in CI. Then a spec change that alters the
public API shows up in review as a diff to openapi.json.
What's generated
- Paths come from each route's full path, with
:idand:id{[0-9]+}converted to{id}. Path parameters are documented fromvalidation.params, or as strings. - Operation ids are
<collection>_<operation>, such astodos_create. - Request bodies come from
validation.body, and query parameters fromvalidation.query. Bodies validated strictly (the default) are documented withadditionalProperties: false. AcontentType: 'form-data'body is documented asmultipart/form-data. - Responses come from
responses, with their Zod schemas. Each route also lists the framework's own errors, using a sharedErrorResponseschema:400when it validates input,401when it requires authentication,403when it requires scopes. Statuses the route documents itself are kept. A response without a schema is documented by itscontent: an object for JSON, a string for text (text/csv), and binary data for anything else (application/pdf,image/*), which documentation tools offer as a download. A stream is described item by item, withitemSchema: each server-sent event ({ event, data, id?, retry? }) or JSON line, and the error sent if it fails once started.itemSchemais OpenAPI 3.2, so passopenapi: '3.2.0'for an API with streams. - Tags default to the spec's
name. - Security applies to every route that isn't
allowAnonymous, including routes withoutauth. WithsecurityByStrategy, a route limited toauth: { strategies: ['jwt'] }lists onlybearerAuth; without it, every route lists every scheme. - Components. Any schema with
.openapi('Name')becomescomponents.schemas.Name. Each spec's main object is also registered: the200schema of itsretrieveroute, named from itsobjectliteral or the spec'smodel.
Options
Prop
Type
Splitting documents
Set group on specs and call generateOpenApiDocumentsByGroup(specs, options)
to get one document per group, such as a public API and an internal one.
Specs without a group are collected under default.
Serving docs
Serve the document from the app and point a viewer such as Scalar at it:
const document = generateOpenApiDocument(specs, openApiOptions);
app.get('/openapi.json', (c) => c.json(document));