Gathering detailed insights and metrics for @fastify/swagger
Gathering detailed insights and metrics for @fastify/swagger
Gathering detailed insights and metrics for @fastify/swagger
Gathering detailed insights and metrics for @fastify/swagger
Swagger documentation generator for Fastify
npm install @fastify/swagger
Typescript
Module System
Node Version
NPM Version
99
Supply Chain
100
Quality
94
Maintenance
100
Vulnerability
100
License
JavaScript (96.13%)
TypeScript (3.87%)
Total Downloads
31,018,437
Last Day
91,646
Last Week
466,100
Last Month
1,968,197
Last Year
20,204,197
971 Stars
687 Commits
210 Forks
21 Watching
8 Branches
143 Contributors
Minified
Minified + Gzipped
Latest Version
9.4.2
Package Id
@fastify/swagger@9.4.2
Unpacked Size
335.57 kB
Size
48.81 kB
File Count
61
NPM Version
10.8.2
Node Version
20.18.0
Publised On
19 Jan 2025
Cumulative downloads
Total Downloads
Last day
-10.1%
91,646
Compared to previous day
Last week
-12.5%
466,100
Compared to previous week
Last month
-9.4%
1,968,197
Compared to previous month
Last year
130.6%
20,204,197
Compared to previous year
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
.
npm i @fastify/swagger
Plugin version | Fastify version |
---|---|
^9.x | ^5.x |
^8.x | ^4.x |
^7.x | ^4.x |
^6.x | ^3.x |
^3.x | ^2.x |
^1.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.
Add it to your project with register
, pass it some options, call the swagger
API, and you are done! Below is an example of how to configure the OpenAPI v3 specification with Fastify Swagger:
1const fastify = require('fastify')() 2 3await fastify.register(require('@fastify/swagger'), { 4 openapi: { 5 openapi: '3.0.0', 6 info: { 7 title: 'Test swagger', 8 description: 'Testing the Fastify swagger API', 9 version: '0.1.0' 10 }, 11 servers: [ 12 { 13 url: 'http://localhost:3000', 14 description: 'Development server' 15 } 16 ], 17 tags: [ 18 { name: 'user', description: 'User related end-points' }, 19 { name: 'code', description: 'Code related end-points' } 20 ], 21 components: { 22 securitySchemes: { 23 apiKey: { 24 type: 'apiKey', 25 name: 'apiKey', 26 in: 'header' 27 } 28 } 29 }, 30 externalDocs: { 31 url: 'https://swagger.io', 32 description: 'Find more info here' 33 } 34 } 35}) 36 37fastify.put('/some-route/:id', { 38 schema: { 39 description: 'post some data', 40 tags: ['user', 'code'], 41 summary: 'qwerty', 42 security: [{ apiKey: [] }], 43 params: { 44 type: 'object', 45 properties: { 46 id: { 47 type: 'string', 48 description: 'user id' 49 } 50 } 51 }, 52 body: { 53 type: 'object', 54 properties: { 55 hello: { type: 'string' }, 56 obj: { 57 type: 'object', 58 properties: { 59 some: { type: 'string' } 60 } 61 } 62 } 63 }, 64 response: { 65 201: { 66 description: 'Successful response', 67 type: 'object', 68 properties: { 69 hello: { type: 'string' } 70 } 71 }, 72 default: { 73 description: 'Default response', 74 type: 'object', 75 properties: { 76 foo: { type: 'string' } 77 } 78 } 79 } 80 } 81}, (req, reply) => { }) 82 83await fastify.ready() 84fastify.swagger()
@fastify/autoload
You need to register @fastify/swagger
before registering routes:
1const fastify = require('fastify')() 2const fastify = fastify() 3await fastify.register(require('@fastify/swagger')) 4fastify.register(require("@fastify/autoload"), { 5 dir: path.join(__dirname, 'routes') 6}) 7await fastify.ready() 8fastify.swagger()
@fastify/swagger
supports two registration modes dynamic
and static
:
dynamic
is the default mode, if you use @fastify/swagger
this way API schemas will be auto-generated from route schemas:
1// All of the below parameters are optional but are included for demonstration purposes 2{ 3 // swagger 2.0 options 4 swagger: { 5 info: { 6 title: String, 7 description: String, 8 version: String 9 }, 10 externalDocs: Object, 11 host: String, 12 schemes: [ String ], 13 consumes: [ String ], 14 produces: [ String ], 15 tags: [ Object ], 16 securityDefinitions: Object 17 }, 18 // openapi 3.0.3 options 19 // openapi: { 20 // info: { 21 // title: String, 22 // description: String, 23 // version: String, 24 // }, 25 // externalDocs: Object, 26 // servers: [ Object ], 27 // components: Object, 28 // security: [ Object ], 29 // tags: [ Object ] 30 // } 31}
All properties detailed in the Swagger (OpenAPI v2) and OpenAPI v3 specifications can be used.
@fastify/swagger
will generate API schemas that adhere to the Swagger specification by default.
If provided an openapi
option it will generate OpenAPI compliant API schemas instead.
Examples of using @fastify/swagger
in dynamic
mode:
static
mode must be configured explicitly. In this mode, @fastify/swagger
serves an already existing Swagger or OpenAPI schema that is passed to it in specification.path
:
1{ 2 mode: 'static', 3 specification: { 4 path: './examples/example-static-specification.yaml', 5 postProcessor: function(swaggerObject) { 6 return swaggerObject 7 }, 8 baseDir: '/path/to/external/spec/files/location', 9 }, 10}
The specification.postProcessor
parameter is optional. It allows you to change your Swagger object on the fly (for example - based on the environment).
It accepts swaggerObject
- a JavaScript object that was parsed from your 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, this is the directory where the main spec file is located. The provided value should be an absolute path without a trailing slash.
An example of using @fastify/swagger
with static
mode enabled can be found here.
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. |
openapi | {} | OpenAPI configuration. |
stripBasePath | true | Strips base path from routes in docs. |
swagger | {} | Swagger configuration. |
transform | null | Transform method for the route's schema and url. documentation. |
transformObject | null | Transform method for the swagger or openapi object before it is rendered. documentation. |
refResolver | {} | Option to manage the $ref s of your application's schemas. Read the $ref documentation |
exposeHeadRoutes | false | Include HEAD routes in the definitions |
decorator | 'swagger' | Overrides the Fastify decorator. documentation. |
By passing a synchronous transform
function you can modify the route's URL and schema.
You may also access the openapiObject
and swaggerObject
Some possible uses of this are:
hide
flag on schema according to your own logic based on URL & schemaThis option is available in dynamic
mode only.
Examples of all the possible uses mentioned:
1const convert = require('joi-to-json') 2 3await fastify.register(require('@fastify/swagger'), { 4 swagger: { ... }, 5 transform: ({ schema, url, route, swaggerObject }) => { 6 const { 7 params, 8 body, 9 querystring, 10 headers, 11 response, 12 ...transformedSchema 13 } = schema 14 let transformedUrl = url 15 16 // Transform the schema as you wish with your own custom logic. 17 // In this example convert is from 'joi-to-json' lib and converts a Joi based schema to json schema 18 if (params) transformedSchema.params = convert(params) 19 if (body) transformedSchema.body = convert(body) 20 if (querystring) transformedSchema.querystring = convert(querystring) 21 if (headers) transformedSchema.headers = convert(headers) 22 if (response) transformedSchema.response = convert(response) 23 24 // can add the hide tag if needed 25 if (url.startsWith('/internal')) transformedSchema.hide = true 26 27 // can transform the url 28 if (url.startsWith('/latest_version/endpoint')) transformedUrl = url.replace('latest_version', 'v3') 29 30 // can add the hide tag for routes that do not match the swaggerObject version 31 if (route?.constraints?.version !== swaggerObject.swagger) transformedSchema.hide = true 32 33 return { schema: transformedSchema, url: transformedUrl } 34 } 35})
You can also attach the transform function on a specific endpoint:
1fastify.get("/", { 2 schema: { ... }, 3 config: { 4 swaggerTransform: ({ schema, url, route, swaggerObject }) => { ... } 5 } 6})
If both a global and a local transform function is available for an endpoint, the endpoint-specific transform function will be used.
The local transform function can be useful if you:
The endpoint-specific transform can be used to "disable" the global transform function by passing in false
instead of a function.
By passing a synchronous transformObject
function you can modify the resulting swaggerObject
or openapiObject
before it is rendered.
1await fastify.register(require('@fastify/swagger'), { 2 swagger: { ... }, 3 transformObject ({ swaggerObject }) => { 4 swaggerObject.info.title = 'Transformed'; 5 return swaggerObject; 6 } 7})
$ref
sWhen this plugin is configured as dynamic
mode, it will resolve all $ref
s in your application's schemas.
This process will create a new in-line schema that is going to reference itself.
This logic step is done to make sure that the generated documentation is valid, otherwise the Swagger UI will try to fetch the schemas from the server or the network and fail.
By default, this option will resolve all $ref
s renaming them to def-${counter}
, but your view models keep the original $id
naming thanks to the title
parameter.
To customize this logic you can pass a refResolver
option to the plugin:
1await fastify.register(require('@fastify/swagger'), { 2 swagger: { ... }, 3 ... 4 refResolver: { 5 buildLocalReference (json, baseUri, fragment, i) { 6 return json.$id || `my-fragment-${i}` 7 } 8 } 9}
For a deep dive into the buildLocalReference
arguments, you may read the documentation.
By passing a string to the decorator
option, you can override the default decorator function (fastify.swagger()
) with a custom one. This allows you to create multiple documents by registering @fastify/swagger
multiple times with different transform
functions:
1// Create an internal Swagger doc 2await fastify.register(require('@fastify/swagger'), { 3 swagger: { ... }, 4 transform: ({ schema, url, route, swaggerObject }) => { 5 const { 6 params, 7 body, 8 querystring, 9 headers, 10 response, 11 ...transformedSchema 12 } = schema 13 let transformedUrl = URL 14 15 // Hide external URLs 16 if (url.startsWith('/external')) transformedSchema.hide = true 17 18 return { schema: transformedSchema, url: transformedUrl } 19 }, 20 decorator: 'internalSwagger' 21}) 22 23// Create an external Swagger doc 24await fastify.register(require('@fastify/swagger'), { 25 swagger: { ... }, 26 transform: ({ schema, url, route, swaggerObject }) => { 27 const { 28 params, 29 body, 30 querystring, 31 headers, 32 response, 33 ...transformedSchema 34 } = schema 35 let transformedUrl = URL 36 37 // Hide internal URLs 38 if (url.startsWith('/internal')) transformedSchema.hide = true 39 40 return { schema: transformedSchema, url: transformedUrl } 41 }, 42 decorator: 'externalSwagger' 43})
You can then call those decorators individually to retrieve them:
fastify.internalSwagger()
fastify.externalSwagger()
It is possible to instruct @fastify/swagger
to include specific HEAD
routes in the definitions
by adding exposeHeadRoute
in the route config, like so:
1 fastify.get('/with-head', { 2 schema: { 3 operationId: 'with-head', 4 response: { 5 200: { 6 description: 'Expected Response', 7 type: 'object', 8 properties: { 9 foo: { type: 'string' } 10 } 11 } 12 } 13 }, 14 config: { 15 swagger: { 16 exposeHeadRoute: true, 17 } 18 } 19 }, () => {})
description
is a required field as per the Swagger specification. If it is not provided then the plugin will automatically generate one with the value 'Default Response'
.
If you supply a description
it will be used for both the response and response body schema, for example:
1fastify.get('/description', { 2 schema: { 3 response: { 4 200: { 5 description: 'response and schema description', 6 type: 'string' 7 } 8 } 9 } 10}, () => {})
Generates this in a Swagger (OpenAPI v2) schema's paths
:
1{ 2 "/description": { 3 "get": { 4 "responses": { 5 "200": { 6 "description": "response and schema description", 7 "schema": { 8 "description": "response and schema description", 9 "type": "string" 10 } 11 } 12 } 13 } 14 } 15}
And this in a OpenAPI v3 schema's paths
:
1{ 2 "/description": { 3 "get": { 4 "responses": { 5 "200": { 6 "description": "response and schema description", 7 "content": { 8 "application/json": { 9 "schema": { 10 "description": "response and schema description", 11 "type": "string" 12 } 13 } 14 } 15 } 16 } 17 } 18 } 19}
If you want to provide different descriptions for the response and response body, use the x-response-description
field alongside description
:
1fastify.get('/responseDescription', { 2 schema: { 3 response: { 4 200: { 5 'x-response-description': 'response description', 6 description: 'schema description', 7 type: 'string' 8 } 9 } 10 } 11}, () => {})
Additionally, if you provide a $ref
in your response schema but no description, the reference's description will be used as a fallback. Note that at the moment, $ref
will only be resolved by matching with $id
and not through complex paths.
Fastify supports both the 2xx
and 3xx
status codes, however Swagger (OpenAPI v2) itself does not.
@fastify/swagger
transforms 2xx
status codes into 200
, but will omit it if a 200
status code has already been declared.
OpenAPI v3 supports the 2xx
syntax so is unaffected.
Example:
1{ 2 response: { 3 '2xx': { 4 description: '2xx', 5 type: 'object' 6 } 7 } 8} 9 10// will become 11{ 12 response: { 13 200: { 14 schema: { 15 description: '2xx', 16 type: 'object' 17 } 18 } 19 } 20}
You can decorate your own response headers by following the below example:
1{ 2 response: { 3 200: { 4 type: 'object', 5 headers: { 6 'X-Foo': { 7 type: 'string' 8 } 9 } 10 } 11 } 12}
Note: You need to specify type
property when you decorate the response headers, otherwise the schema will be modified by Fastify.
Note: not supported by Swagger (OpenAPI v2), only OpenAPI v3
Different content types responses are supported by @fastify/swagger
and @fastify
.
Please use content
for the response otherwise Fastify itself will fail to compile the schema:
1{ 2 response: { 3 200: { 4 description: 'Description and all status-code based properties are working', 5 content: { 6 'application/json': { 7 schema: { 8 name: { type: 'string' }, 9 image: { type: 'string' }, 10 address: { type: 'string' } 11 } 12 }, 13 'application/vnd.v1+json': { 14 schema: { 15 fullName: { type: 'string' }, 16 phone: { type: 'string' } 17 } 18 } 19 } 20 } 21 } 22}
Empty body responses are supported by @fastify/swagger
.
Please specify type: 'null'
for the response otherwise Fastify itself will fail to compile the schema:
1{ 2 response: { 3 204: { 4 type: 'null', 5 description: 'No Content' 6 }, 7 503: { 8 type: 'null', 9 description: 'Service Unavailable' 10 } 11 } 12}
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 provides some options beyond those provided by the JSON schema specification for specifying the shape of parameters. A prime example of this is the collectionFormat
option for specifying how to encode parameters that should be handled as arrays of values.
These encoding options only change how Swagger UI presents its documentation and how it generates curl
commands when the Try it out
button is clicked.
Depending on which options you set in your schema, you may also need to change the default query string parser used by Fastify so that it produces a JavaScript object that will conform to the schema.
As far as arrays are concerned, the default query string parser conforms to the collectionFormat: "multi"
specification.
If you were to select collectionFormat: "csv"
, you would have to replace the default query string parser with one that parses CSV parameter values into arrays.
The same applies to the other parts of a request that OpenAPI calls "parameters" and which are not encoded as JSON in a request.
You can also apply a different serialization style
and explode
as specified here.
@fastify/swagger
supports these options as shown in this example:
1// Need to add a collectionFormat keyword to ajv in fastify instance 2const fastify = Fastify({ 3 ajv: { 4 customOptions: { 5 keywords: ['collectionFormat'] 6 } 7 } 8}) 9 10fastify.route({ 11 method: 'GET', 12 url: '/', 13 schema: { 14 querystring: { 15 type: 'object', 16 required: ['fields'], 17 additionalProperties: false, 18 properties: { 19 fields: { 20 type: 'array', 21 items: { 22 type: 'string' 23 }, 24 minItems: 1, 25 // 26 // Note that this is an OpenAPI version 2 configuration option. The 27 // options changed in version 3. 28 // 29 // Put `collectionFormat` on the same property which you are defining 30 // as an array of values. (i.e. `collectionFormat` should be a sibling 31 // of the `type: "array"` specification.) 32 collectionFormat: 'multi' 33 } 34 }, 35 // OpenAPI 3 serialization options 36 explode: false, 37 style: "deepObject" 38 } 39 }, 40 handler (request, reply) { 41 reply.send(request.query.fields) 42 } 43})
There is a complete runnable example here.
Note: not supported by Swagger (OpenAPI v2), only OpenAPI v3
http://localhost/?filter={"foo":"baz","bar":"qux"}
IMPORTANT CAVEAT You will need to change the default query string parser used by Fastify so that it produces a JavaScript object that will conform to the schema. See example.
1fastify.route({ 2 method: 'GET', 3 url: '/', 4 schema: { 5 querystring: { 6 type: 'object', 7 required: ['filter'], 8 additionalProperties: false, 9 properties: { 10 filter: { 11 type: 'object', 12 required: ['foo'], 13 properties: { 14 foo: { type: 'string' }, 15 bar: { type: 'string' } 16 }, 17 'x-consume': 'application/json' 18 } 19 } 20 } 21 }, 22 handler (request, reply) { 23 reply.send(request.query.filter) 24 } 25})
Will generate this in the OpenAPI v3 schema's paths
:
1{ 2 "/": { 3 "get": { 4 "parameters": [ 5 { 6 "in": "query", 7 "name": "filter", 8 "required": true, 9 "content": { 10 "application/json": { 11 "schema": { 12 "type": "object", 13 "required": [ 14 "foo" 15 ], 16 "properties": { 17 "foo": { 18 "type": "string" 19 }, 20 "bar": { 21 "type": "string" 22 } 23 } 24 } 25 } 26 } 27 } 28 ] 29 } 30 } 31}
Route parameters in Fastify are called params, these are values included in the URL of the requests, for example:
1fastify.route({ 2 method: 'GET', 3 url: '/:id', 4 schema: { 5 params: { 6 type: 'object', 7 properties: { 8 id: { 9 type: 'string', 10 description: 'user id' 11 } 12 } 13 } 14 }, 15 handler (request, reply) { 16 reply.send(request.params.id) 17 } 18})
Will generate this in the Swagger (OpenAPI v2) schema's paths
:
1{ 2 "/{id}": { 3 "get": { 4 "parameters": [ 5 { 6 "type": "string", 7 "description": "user id", 8 "required": true, 9 "in": "path", 10 "name": "id" 11 } 12 ], 13 "responses": { 14 "200": { 15 "description": "Default Response" 16 } 17 } 18 } 19 } 20}
Will generate this in the OpenAPI v3 schema's paths
:
1{ 2 "/{id}": { 3 "get": { 4 "parameters": [ 5 { 6 "schema": { 7 "type": "string" 8 }, 9 "in": "path", 10 "name": "id", 11 "required": true, 12 "description": "user id" 13 } 14 ], 15 "responses": { 16 "200": { 17 "description": "Default Response" 18 } 19 } 20 } 21 } 22}
When params
is not present in the schema, or a schema is not provided, parameters are automatically generated, for example:
1fastify.route({ 2 method: 'POST', 3 url: '/:id', 4 handler (request, reply) { 5 reply.send(request.params.id) 6 } 7})
Will generate this in the Swagger (OpenAPI v2) schema's paths
:
1{ 2 "/{id}": { 3 "get": { 4 "parameters": [ 5 { 6 "type": "string", 7 "required": true, 8 "in": "path", 9 "name": "id" 10 } 11 ], 12 "responses": { 13 "200": { 14 "description": "Default Response" 15 } 16 } 17 } 18 } 19}
Will generate this in the OpenAPI v3 schema's paths
:
1{ 2 "/{id}": { 3 "get": { 4 "parameters": [ 5 { 6 "schema": { 7 "type": "string" 8 }, 9 "in": "path", 10 "name": "id", 11 "required": true 12 } 13 ], 14 "responses": { 15 "200": { 16 "description": "Default Response" 17 } 18 } 19 } 20 } 21}
Note: not supported by Swagger (OpenAPI v2), only OpenAPI v3
OpenAPI v3 Links are added by adding a links
property to the top-level options of a route. See:
1fastify.get('/user/:id', { 2 schema: { 3 params: { 4 type: 'object', 5 properties: { 6 id: { 7 type: 'string', 8 description: 'the user identifier, as userId' 9 } 10 }, 11 required: ['id'] 12 }, 13 response: { 14 200: { 15 type: 'object', 16 properties: { 17 uuid: { 18 type: 'string', 19 format: 'uuid' 20 } 21 } 22 } 23 } 24 }, 25 links: { 26 // The status code must match the one in the response 27 200: { 28 address: { 29 // See the OpenAPI documentation 30 operationId: 'getUserAddress', 31 parameters: { 32 id: '$request.path.id' 33 } 34 } 35 } 36 } 37}, () => {}) 38 39fastify.get('/user/:id/address', { 40 schema: { 41 operationId: 'getUserAddress', 42 params: { 43 type: 'object', 44 properties: { 45 id: { 46 type: 'string', 47 description: 'the user identifier, as userId' 48 } 49 }, 50 required: ['id'] 51 }, 52 response: { 53 200: { 54 type: 'string' 55 } 56 } 57 } 58}, () => {})
There are two ways to hide a route from the Swagger UI:
{ hide: true }
to the schema object inside the route declaration.hiddenTag
options property inside the route declaration. Default is X-HIDDEN
.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 will return a YAML string.
You can integrate this plugin with @fastify/helmet
with some little work.
@fastify/helmet
options example:
1.register(helmet, instance => { 2 return { 3 contentSecurityPolicy: { 4 directives: { 5 ...helmet.contentSecurityPolicy.getDefaultDirectives(), 6 "form-action": ["'self'"], 7 "img-src": ["'self'", "data:", "validator.swagger.io"], 8 "script-src": ["'self'"].concat(instance.swaggerCSP.script), 9 "style-src": ["'self'", "https:"].concat( 10 instance.swaggerCSP.style 11 ), 12 } 13 } 14 } 15})
Note: OpenAPI and JSON Schema have different examples field formats.
Array with examples from JSON Schema converted to OpenAPI example
or examples
field automatically with generated names (example1, example2...):
1fastify.route({ 2 method: 'POST', 3 url: '/', 4 schema: { 5 querystring: { 6 type: 'object', 7 required: ['filter'], 8 properties: { 9 filter: { 10 type: 'object', 11 required: ['foo'], 12 properties: { 13 foo: { type: 'string' }, 14 bar: { type: 'string' } 15 }, 16 examples: [ 17 { foo: 'bar', bar: 'baz' }, 18 { foo: 'foo', bar: 'bar' } 19 ] 20 } 21 }, 22 examples: [ 23 { filter: { foo: 'bar', bar: 'baz' } } 24 ] 25 } 26 }, 27 handler (request, reply) { 28 reply.send(request.query.filter) 29 } 30})
Will generate this in the OpenAPI v3 schema's path
:
1"/": { 2 "post": { 3 "requestBody": { 4 "content": { 5 "application/json": { 6 "schema": { 7 "type": "object", 8 "required": ["filter"], 9 "properties": { 10 "filter": { 11 "type": "object", 12 "required": ["foo"], 13 "properties": { 14 "foo": { "type": "string" }, 15 "bar": { "type": "string" } 16 }, 17 "example": { "foo": "bar", "bar": "baz" } 18 } 19 } 20 }, 21 "examples": { 22 "example1": { 23 "value": { "filter": { "foo": "bar", "bar": "baz" } } 24 }, 25 "example2": { 26 "value": { "filter": { "foo": "foo", "bar": "bar" } } 27 } 28 } 29 } 30 }, 31 "required": true 32 }, 33 "responses": { "200": { "description": "Default Response" } } 34 } 35}
If you want to set your own names or add descriptions to the examples of schemas, you can use x-examples
field to set examples in OpenAPI format:
1// Need to add a new allowed keyword to ajv in fastify instance 2const fastify = Fastify({ 3 ajv: { 4 plugins: [ 5 function (ajv) { 6 ajv.addKeyword({ keyword: 'x-examples' }) 7 } 8 ] 9 } 10}) 11 12fastify.route({ 13 method: 'POST', 14 url: '/feed-animals', 15 schema: { 16 body: { 17 type: 'object', 18 required: ['animals'], 19 properties: { 20 animals: { 21 type: 'array', 22 items: { 23 type: 'string' 24 }, 25 minItems: 1, 26 } 27 }, 28 "x-examples": { 29 Cats: { 30 summary: "Feed cats", 31 description: 32 "A longer **description** of the options with cats", 33 value: { 34 animals: ["Tom", "Garfield", "Felix"] 35 } 36 }, 37 Dogs: { 38 summary: "Feed dogs", 39 value: { 40 animals: ["Spike", "Odie", "Snoopy"] 41 } 42 } 43 } 44 } 45 }, 46 handler (request, reply) { 47 reply.send(request.body.animals) 48 } 49})
$id
and $ref
usageTo start development run:
npm i
npm run prepare
So that swagger-ui static folder will be generated for you.
@fastify/static
serves swagger-ui
static files, then calls /docs/json
to get the Swagger file and render it.
The /docs/json
endpoint in dynamic mode produces a single swagger.json
file resolving all your references.
This project is kindly sponsored by:
Licensed under MIT.
No vulnerabilities found.
Reason
30 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 8
Details
Reason
Found 8/28 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More@fastify/swagger-ui
Serve Swagger-ui for Fastify
fastify-swagger
`fastify-swagger@5.2.0` has been deprecated. Please use `@fastify/swagger@6.0.0` instead.
swagger-stats
API Telemetry and APM. Trace API calls and Monitor API performance, health and usage statistics in Node.js Microservices, based on express routes and Swagger (Open API) specification
@lineupr/fastify-swagger-ui
Serve Swagger-ui for Fastify