Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
@fastify/swagger-ui
Advanced tools
@fastify/swagger-ui is a Fastify plugin that serves an interactive Swagger UI for your Fastify application. It allows you to visualize and interact with the API's resources without having to manually create documentation.
Serve Swagger UI
This feature allows you to serve a Swagger UI for your Fastify application. The code sample demonstrates how to set up the Swagger UI with a custom route prefix and configuration options.
const fastify = require('fastify')();
const swaggerUi = require('@fastify/swagger-ui');
fastify.register(require('@fastify/swagger'), {
routePrefix: '/documentation',
swagger: {
info: {
title: 'Test API',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
host: 'localhost:3000',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json']
},
exposeRoute: true
});
fastify.register(swaggerUi, {
routePrefix: '/docs',
uiConfig: {
docExpansion: 'full',
deepLinking: false
},
staticCSP: true,
transformStaticCSP: (header) => header
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Custom UI Configuration
This feature allows you to customize the Swagger UI configuration. The code sample shows how to set up the Swagger UI with custom UI settings such as `docExpansion` and `deepLinking`.
const fastify = require('fastify')();
const swaggerUi = require('@fastify/swagger-ui');
fastify.register(require('@fastify/swagger'), {
routePrefix: '/documentation',
swagger: {
info: {
title: 'Test API',
description: 'Testing the Fastify swagger API',
version: '0.1.0'
},
host: 'localhost:3000',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json']
},
exposeRoute: true
});
fastify.register(swaggerUi, {
routePrefix: '/docs',
uiConfig: {
docExpansion: 'list',
deepLinking: true
},
staticCSP: true,
transformStaticCSP: (header) => header
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
swagger-ui-express is a package that serves Swagger UI for Express applications. It provides similar functionality to @fastify/swagger-ui but is designed for use with the Express framework instead of Fastify.
redoc is an alternative to Swagger UI that provides a more modern and responsive interface for API documentation. It can be used with various frameworks and offers features like interactive documentation and customizable themes.
swagger-jsdoc is a package that generates Swagger definitions from JSDoc comments in your code. It can be used with various frameworks, including Fastify, to create Swagger documentation and serve it using Swagger UI or other tools.
A Fastify plugin for serving Swagger UI.
Supports Fastify versions 4.x
.
npm i @fastify/swagger-ui
Add it with @fastify/swagger
to your project with register
, pass it some options, call the swagger
API, and you are done!
const fastify = require('fastify')()
await fastify.register(require('@fastify/swagger'))
await fastify.register(require('@fastify/swagger-ui'), {
routePrefix: '/documentation',
uiConfig: {
docExpansion: 'full',
deepLinking: false
},
uiHooks: {
onRequest: function (request, reply, next) { next() },
preHandler: function (request, reply, next) { next() }
},
staticCSP: true,
transformStaticCSP: (header) => header,
transformSpecification: (swaggerObject, request, reply) => { return swaggerObject },
transformSpecificationClone: true
})
fastify.put('/some-route/:id', {
schema: {
description: 'post some data',
tags: ['user', 'code'],
summary: 'qwerty',
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
body: {
type: 'object',
properties: {
hello: { type: 'string' },
obj: {
type: 'object',
properties: {
some: { type: 'string' }
}
}
}
},
response: {
201: {
description: 'Successful response',
type: 'object',
properties: {
hello: { type: 'string' }
}
},
default: {
description: 'Default response',
type: 'object',
properties: {
foo: { type: 'string' }
}
}
},
security: [
{
"apiKey": []
}
]
}
}, (req, reply) => {})
await fastify.ready()
Option | Default | Description |
---|---|---|
baseDir | undefined | Specify the directory where all spec files that are included in the main one using $ref will be located. By default, this is the directory where the main spec file is located. Provided value should be an absolute path without trailing slash. |
initOAuth | {} | Configuration options for Swagger UI initOAuth. |
routePrefix | '/documentation' | Overwrite the default Swagger UI route prefix. |
staticCSP | false | Enable CSP header for static resources. |
transformStaticCSP | undefined | Synchronous function to transform CSP header for static resources if the header has been previously set. |
transformSpecification | undefined | Synchronous function to transform the swagger document. |
transformSpecificationClone | true | Provide a deepcloned swaggerObject to transformSpecification |
uiConfig | {} | Configuration options for Swagger UI. |
uiHooks | {} | Additional hooks for the documentation's routes. You can provide the onRequest and preHandler hooks with the same route's options interface. |
theme | {} | Add custom JavaScript and CSS to the Swagger UI web page |
logLevel | info | Allow to define route log level. |
The plugin will expose the documentation with the following APIs:
URL | Description |
---|---|
'/documentation/json' | The JSON object representing the API |
'/documentation/yaml' | The YAML object representing the API |
'/documentation/' | The swagger UI |
'/documentation/*' | External files that you may use in $ref |
To configure Swagger UI, you need to modify the uiConfig
option.
It's important to ensure that functions are self-contained. Keep in mind that
you cannot modify the backend code within the uiConfig
functions, as these
functions are processed only by the browser. You can reference the Swagger UI
element using ui
, which is assigned to window.ui
.
const fastify = require('fastify')()
await fastify.register(require('@fastify/swagger'))
await fastify.register(require('@fastify/swagger-ui'), {
uiConfig: {
onComplete: function () {
alert('ui has type of ' + typeof ui) // 'ui has type of object'
alert('fastify has type of ' + typeof fastify) // 'fastify has type of undefined'
alert('window has type of ' + typeof window) // 'window has type of object'
alert('global has type of ' + typeof global) // 'global has type of undefined'
}
}
})
There can be use cases, where you want to modify the swagger definition on request. E.g. you want to modify the server definition based on the hostname of the request object. In such a case you can utilize the transformSpecification-option.
const fastify = require('fastify')()
await fastify.register(require('@fastify/swagger'))
await fastify.register(require('@fastify/swagger-ui'), {
transformSpecification: (swaggerObject, req, reply) => {
swaggerObject.host = req.hostname
return swaggerObject
}
})
By default fastify.swagger() will be deepcloned and passed to the transformSpecification-function, as fastify.swagger() returns a mutatable Object. You can disable the deepcloning by setting transformSpecificationClone to false. This is useful, if you want to handle the deepcloning in the transformSpecification function.
const fastify = require('fastify')()
const LRU = require('tiny-lru').lru
const rfdc = require('rfdc')()
await fastify.register(require('@fastify/swagger'))
const swaggerLru = new LRU(1000)
await fastify.register(require('@fastify/swagger-ui'), {
transformSpecificationClone: false,
transformSpecification: (swaggerObject, req, reply) => {
if (swaggerLru.has(req.hostname)) {
return swaggerLru.get(req.hostname)
}
const clonedSwaggerObject = rfdc(swaggerObject)
clonedSwaggerObject.host = req.hostname
swaggerLru.set(req.hostname, clonedSwaggerObject)
return clonedSwaggerObject
}
})
You can add custom JavaScript and CSS to the Swagger UI web page by using the theme option.
const fastify = require('fastify')()
fastify.register(require('@fastify/swagger'))
await fastify.register(require('@fastify/swagger-ui'), {
theme: {
js: [
{ filename: 'special.js', content: 'alert("client javascript")' }
],
css: [
{ filename: 'theme.css', content: '* { border: 1px red solid; }' }
],
favicon: [
{
filename: 'favicon.png',
rel: 'icon',
sizes: '16x16',
type: 'image/png',
content: Buffer.from('iVBOR...', 'base64')
}
]
}
})
Licensed under MIT.
FAQs
Serve Swagger-ui for Fastify
The npm package @fastify/swagger-ui receives a total of 175,026 weekly downloads. As such, @fastify/swagger-ui popularity was classified as popular.
We found that @fastify/swagger-ui demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 18 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.