A Fastify plugin for serving Swagger (OpenAPI v2) or OpenAPI v3 schemas, which are automatically generated from your route schemas, or an existing Swagger/OpenAPI schema.
If you are looking for a plugin to generate routes from an existing OpenAPI schema, check out fastify-openapi-glue.
The following plugins serve Swagger/OpenAPI front-ends based on the swagger definitions generated by this plugin:
See the migration guide for migrating from @fastify/swagger version <=7.x to version >=8.x.
Install
npm i @fastify/swagger
Compatibility
Plugin version
Fastify version
>=9.x
^5.x
>=7.x <9.x
^4.x
^6.x
^3.x
>=3.x <6.x
^2.x
>=1.x <3.x
^1.x
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin
in the table above.
See Fastify's LTS policy for more details.
Usage
Add it with register, pass it options, call the swagger API, and you are done! Below is an example of configuring the OpenAPI v3 specification with Fastify Swagger:
ℹ️ Note: @fastify/swagger must be registered before any routes to ensure proper route discovery. Routes registered before this plugin will not appear in the generated documentation.
With @fastify/autoload
Register @fastify/swagger before routes are loaded with @fastify/autoload:
All properties in the Swagger (OpenAPI v2) and OpenAPI v3 specifications can be used.
@fastify/swagger generates API schemas adhering to the Swagger specification by default.
Providing an openapi option generates OpenAPI compliant API schemas instead.
The OpenAPI version of the generated document is taken from the openapi.openapi string (3.0.3 by default).
Set it to 3.1.0 or 3.2.0 to generate a document for that version; the top-level properties introduced by newer
versions (webhooks in 3.1, $self and the summary, parent and kind properties of the tag object in 3.2) are
passed through to the generated document. Routes registered with the QUERY HTTP method (OpenAPI 3.2) are documented
like any other method with a request body.
When the version is 3.2.0 or higher, the routes of the HTTP methods without a fixed field in the Path Item Object
(eg: the ones added with fastify.addHttpMethod(), like PROPFIND) are listed in its additionalOperations map.
Older OpenAPI versions cannot describe those methods.
The swagger and openapi option types come from openapi-types.
The OpenAPI specification allows extensions (x-* properties) on most objects, but the openapi-types interfaces do not declare an index signature for them, so adding e.g. x-logo to the info object fails to compile.
The plugin passes these properties through unchanged at runtime; only the type definitions need to be extended.
To do so, augment the openapi-types module (not @fastify/swagger) in a .d.ts file of your project.
Use the OpenAPIV3 namespace for the openapi option (it covers OpenAPI 3.1 documents too, as the OpenAPIV3_1 types are derived from it) and the OpenAPIV2 namespace for the swagger option:
ℹ️ Note: openapi-types must be resolvable from your project for the augmentation to be applied.
Package managers with a strict node_modules layout (e.g. pnpm) do not expose transitive dependencies, and in that case the augmentation is silently ignored: add openapi-types to your devDependencies.
Documenting routes not registered in Fastify
Some routes are served by the application but are not registered through Fastify's router (e.g., routes added by a third-party middleware), so dynamic mode cannot discover them.
These routes can be described by hand using the paths property of the openapi (or swagger) option. The routes discovered from Fastify are then merged on top of it:
await fastify.register(require('@fastify/swagger'), { openapi: { info: { title: 'My API', version: '1.0.0' }, paths: { '/auth/signin': { post: { tags: ['auth'], summary: 'Sign in', responses: { 200: { description: 'OK' } } } } } }})// this route is generated from its schema and added next to `/auth/signin`fastify.get('/users', { schema: { ... } }, handler)
If a path in paths has the same URL as a registered route, their methods are merged. When both define the same method, the registered route takes precedence.
The paths can also be loaded from an existing specification file:
The specification.postProcessor parameter is optional and allows modifying the Swagger object on the fly, e.g., based on the environment.
It accepts swaggerObject - a JavaScript object parsed from a yaml or json file and should return a Swagger schema object.
specification.baseDir allows specifying the directory where all spec files that are included in the main one using $ref will be located.
By default, it is the directory of the main spec file. The value should be an absolute path without a trailing slash.
An example of using @fastify/swagger with static mode enabled can be found here.
Options
Option
Default
Description
hiddenTag
X-HIDDEN
Tag to control hiding of routes.
hideUntagged
false
If true remove routes without tags from resulting Swagger/OpenAPI schema file.
Pass a synchronous transform function to modify the route's URL and schema.
openapiObject and swaggerObject are also available.
Some possible uses of this are:
Adding the hide flag to the schema based on URL and schema logic
Altering the route URL to suit the API spec
Transforming different schemas (e.g., Joi) to standard JSON schemas
Hiding routes based on version constraints
This option is available in dynamic mode only.
Examples of all the possible uses mentioned:
const convert = require('joi-to-json')await fastify.register(require('@fastify/swagger'), { swagger: { ... }, transform: ({ schema, url, route, swaggerObject }) => { const { params, body, querystring, headers, response, ...transformedSchema } = schema let transformedUrl = url // Transform the schema as you wish with your own custom logic. // In this example convert is from 'joi-to-json' lib and converts a Joi based schema to json schema if (params) transformedSchema.params = convert(params) if
The transform function can also be attached to a specific endpoint:
If both global and local transform functions are available for an endpoint, the endpoint-specific transform function is used.
The local transform function is useful for adding information to a specific endpoint, applying different transformations, or ignoring the global transform function.
The global transform function can be disabled by passing false instead of a function.
Transform Object
By passing a synchronous transformObject function you can modify the resulting swaggerObject or openapiObject before it is rendered.
In dynamic mode, this plugin resolves all $refs in the application's schemas, creating a new in-line schema that references itself.
This ensures the generated documentation is valid, preventing Swagger UI from failing to fetch schemas from the server or network.
By default, this option resolves all $refs, renaming them to def-${counter}, while view models keep the original $id naming using the title parameter.
This logic can be customized by passing a refResolver option to the plugin:
For details on buildLocalReference arguments, see the documentation.
definitions and $defs of a shared schema
Swagger and OpenAPI do not allow the definitions and $defs keywords inside a schema object.
The definitions nested into a schema added with fastify.addSchema() are moved next to it, named <schema>-<key>
(a numeric suffix is appended when the name is already taken), and the $refs pointing to them are updated:
fastify.addSchema({ $id: 'http://example.com/common.json', type: 'object', definitions: { address: { $id: '#address', type: 'object', properties: { city: { type: 'string' } } } }})// both are rendered as `#/components/schemas/def-0-address` (`#/definitions/def-0-address` with Swagger){ $ref: 'http://example.com/common.json#/definitions/address' }{ $ref: 'http://example.com/common.json#address' }
A reference to an anchor (a fragment-only $id like #address) must be written as the $id of the shared schema
followed by the anchor, or as #address from inside the shared schema itself.
Decorator
The default decorate function (fastify.swagger()) can be overridden by passing a string to the decorator option. This allows creating multiple documents by registering @fastify/swagger multiple times with different transform functions:
Response description and response body description
description is required by the Swagger specification. If not provided, the plugin defaults to 'Default Response'.
If a description is supplied, it will be used for both the response and response body schema:
If a $ref is provided in the response schema without a description, the reference's description will be used as a fallback. Currently, $ref is resolved by matching with $id only, not through complex paths.
Status code 2xx
Fastify supports 2xx and 3xx status codes, but Swagger (OpenAPI v2) does not.
@fastify/swagger transforms 2xx into 200, omitting it if 200 is already declared.
OpenAPI v3 supports 2xx syntax so is unaffected.
Response headers can be decorated with the following example.
Specify the type property when decorating response headers to prevent schema modification by Fastify.
Different content types are supported by @fastify/swagger and @fastify.
Use content for the response to prevent Fastify from failing to compile the schema:
JSON Schema describes null with type: 'null', which does not exist in OpenAPI 3.0.
When the document version is 3.0.x (the default), @fastify/swagger converts it to nullable:
In OpenAPI 3.0 nullable: true only adds null to the type defined in the same Schema Object:
next to anyOf, oneOf or $ref it has no effect. For this reason a union is simplified only
when its single non-null member defines a type, otherwise the null member is kept as a nullable
schema restricted to enum: [null].
The array form of type does not exist in OpenAPI 3.0 either, so it is converted even when null is not one of the types.
The same applies to oneOf. Schemas are left untouched in OpenAPI 3.1 documents, where type: 'null' is valid.
OpenAPI Parameter Options
ℹ️ Note: OpenAPI's terminology differs from Fastify's. OpenAPI uses "parameter" to refer to parts of a request that in Fastify's validation documentation are called "querystring", "params", and "headers".
OpenAPI extends the JSON schema specification with options like collectionFormat for encoding array parameters.
These encoding options only affect how Swagger UI presents documentation and generates curl commands.
Depending on the schema options, you may need to change Fastify's default query string parser to produce a JavaScript object conforming to the schema.
The default parser conforms to collectionFormat: "multi".
For collectionFormat: "csv", replace the default parser with one that parses CSV values into arrays. This applies to other request parts that OpenAPI calls "parameters" and are not encoded as JSON.
Different serialization style and explode can also be applied as specified here.
@fastify/swagger supports these options as shown in this example:
// Need to add a collectionFormat keyword to ajv in fastify instanceconst fastify = Fastify({ ajv: { customOptions: { keywords: ['collectionFormat'] } }})fastify.route({ method: 'GET', url: '/', schema: { querystring: { type: 'object', required: ['fields'], additionalProperties: false, properties: { fields: { type: 'array', items: { type: 'string' }, minItems:
Add OpenAPI v3 Links by adding a links property to the top-level options of a route. See:
fastify.get('/user/:id', { schema: { params: { type: 'object', properties: { id: { type: 'string', description: 'the user identifier, as userId' } }, required: ['id'] }, response: { 200: { type: 'object', properties: { uuid: { type: 'string', format: 'uuid' } } } } }, links: { // The status code must match the one in the response
Hide a route
There are two ways to hide a route from the Swagger UI:
Pass { hide: true } to the schema object inside the route declaration.
Use the tag declared in hiddenTag options property inside the route declaration. Default is X-HIDDEN.
Swagger function options
Registering @fastify/swagger decorates the fastify instance with fastify.swagger(), which returns a JSON object representing the API.
If { yaml: true } is passed to fastify.swagger() it returns a YAML string.
Integration
This plugin can be integrated with @fastify/helmet with minimal effort: