fastify-swagger

Serve Swagger/OpenAPI documentation for Fastify, supporting dynamic generation

Usage no npm install needed!

<script type="module">
  import fastifySwagger from 'https://cdn.skypack.dev/fastify-swagger';
</script>

README

fastify-swagger

NPM version CI workflow Known Vulnerabilities js-standard-style

A Fastify plugin for serving a Swagger UI, using Swagger (OpenAPI v2) or OpenAPI v3 schemas automatically generated from your route schemas, or from an existing Swagger/OpenAPI schema.

Supports Fastify versions >=3.0.0. For fastify@2, please refer to branch@2.x and for fastify@1.9, please refer to branch@1.x.

If you are looking for a plugin to generate routes from an existing OpenAPI schema, check out fastify-swaggergen.

Install

npm i fastify-swagger --save

Usage

Add it to your project with register, pass it some options, call the swagger API, and you are done!

const fastify = require('fastify')()

fastify.register(require('fastify-swagger'), {
  routePrefix: '/documentation',
  swagger: {
    info: {
      title: 'Test swagger',
      description: 'Testing the Fastify swagger API',
      version: '0.1.0'
    },
    externalDocs: {
      url: 'https://swagger.io',
      description: 'Find more info here'
    },
    host: 'localhost',
    schemes: ['http'],
    consumes: ['application/json'],
    produces: ['application/json'],
    tags: [
      { name: 'user', description: 'User related end-points' },
      { name: 'code', description: 'Code related end-points' }
    ],
    definitions: {
      User: {
        type: 'object',
        required: ['id', 'email'],
        properties: {
          id: { type: 'string', format: 'uuid' },
          firstName: { type: 'string' },
          lastName: { type: 'string' },
          email: {type: 'string', format: 'email' }
        }
      }
    },
    securityDefinitions: {
      apiKey: {
        type: 'apiKey',
        name: 'apiKey',
        in: 'header'
      }
    }
  },
  uiConfig: {
    docExpansion: 'full',
    deepLinking: false
  },
  uiHooks: {
    onRequest: function (request, reply, next) { next() },
    preHandler: function (request, reply, next) { next() }
  },
  staticCSP: true,
  transformStaticCSP: (header) => header,
  exposeRoute: 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) => {})

fastify.ready(err => {
  if (err) throw err
  fastify.swagger()
})

API

Register options

Modes

fastify-swagger supports two registration modes dynamic and static:

Dynamic

dynamic is the default mode, if you use fastify-swagger this way API schemas will be auto-generated from route schemas:

// All of the below parameters are optional but are included for demonstration purposes
{
  // swagger 2.0 options
  swagger: {
    info: {
      title: String,
      description: String,
      version: String
    },
    externalDocs: Object,
    host: String,
    schemes: [ String ],
    consumes: [ String ],
    produces: [ String ],
    tags: [ Object ],
    securityDefinitions: Object
  },
  // openapi 3.0.3 options
  // openapi: {
  //   info: {
  //     title: String,
  //     description: String,
  //     version: String,
  //   },
  //   externalDocs: Object,
  //   servers: [ Object ],
  //   components: Object,
  //   security: [ Object ],
  //   tags: [ Object ]
  // }
}

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

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:

{
  mode: 'static',
  specification: {
    path: './examples/example-static-specification.yaml',
    postProcessor: function(swaggerObject) {
      return swaggerObject
    },
    baseDir: '/path/to/external/spec/files/location',
  },
}

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. Provided value should be an absolute path without trailing slash.

An example of using fastify-swagger with static mode enabled can be found here.

Options

Option Default Description
exposeRoute false Exposes documentation route.
hiddenTag X-HIDDEN Tag to control hiding of routes.
hideUntagged false If true remove routes without tags from resulting Swagger/OpenAPI schema file.
initOAuth {} Configuration options for Swagger UI initOAuth.
openapi {} OpenAPI configuration.
routePrefix '/documentation' Overwrite the default Swagger UI route prefix.
staticCSP false Enable CSP header for static resources.
stripBasePath true Strips base path from routes in docs.
swagger {} Swagger configuration.
transform null Transform method for schema.
transformStaticCSP undefined Synchronous function to transform CSP header for static resources if the header has been previously set.
uiConfig {} Configuration options for Swagger UI. Must be literal values, see #5710.
uiHooks {} Additional hooks for the documentation's routes. You can provide the onRequest and preHandler hooks with the same route's options interface.
refResolver {} Option to manage the $refs of your application's schemas. Read the $ref documentation

If you set exposeRoute to true 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

Transforms

To use different schemas such as Joi you can pass a synchronous transform method in the options to convert them back to standard JSON schemas expected by this plugin to generate the documentation (dynamic mode only).

const convert = require('joi-to-json')

fastify.register(require('fastify-swagger'), {
  swagger: { ... },
  ...
  transform: schema => {
    const {
      params = undefined,
      body = undefined,
      querystring = undefined,
      ...others
    } = schema
    const transformed = { ...others }
    if (params) transformed.params = convert(params)
    if (body) transformed.body = convert(body)
    if (querystring) transformed.querystring = convert(querystring)
    return transformed
  }
}

Managing your $refs

When this plugin is configured as dynamic mode, it will resolve all $refs in your application's schemas. This process will create an 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 $refs 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:

fastify.register(require('fastify-swagger'), {
  swagger: { ... },
  ...
  refResolver: {
    buildLocalReference (json, baseUri, fragment, i) {
      return json.$id || `my-fragment-${i}`
    }
  }
}

To deep down the buildLocalReference arguments, you may read the documentation.

Route options

Response Options

Response description and response body description

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:

fastify.get('/description', {
  schema: {
    response: {
      200: {
        description: 'response and schema description',
        type: 'string'
      }
    }
  }
}, () => {})

Generates this in a Swagger (OpenAPI v2) schema's paths:

{
  "/description": {
    "get": {
      "responses": {
        "200": {
          "description": "response and schema description",
          "schema": {
            "description": "response and schema description",
            "type": "string"
          }
        }
      }
    }
  }
}

And this in a OpenAPI v3 schema's paths:

{
  "/description": {
    "get": {
      "responses": {
        "200": {
          "description": "response and schema description",
          "content": {
            "application/json": {
              "schema": {
                "description": "response and schema description",
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}

If you want to provide different descriptions for the response and response body, use the x-response-description field alongside description:

fastify.get('/responseDescription', {
  schema: {
    response: {
      200: {
        'x-response-description': 'response description',
        description: 'schema description',
        type: 'string'
      }
    }
  }
}, () => {})

Status code 2xx

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:

{
  response: {
    '2xx': {
      description: '2xx',
      type: 'object'
    }
  }
}

// will become
{
  response: {
    200: {
      schema: {
        description: '2xx',
        type: 'object'
      }
    }
  }
}

Response headers

You can decorate your own response headers by following the below example:

{
  response: {
    200: {
      type: 'object',
      headers: {
        'X-Foo': {
          type: 'string'
        }
      }
    }
  }
}

Note: You need to specify type property when you decorate the response headers, otherwise the schema will be modified by Fastify.

Empty Body Responses

Empty body responses are supported by fastify-swagger. Please specify type: 'null' for the response otherwise Fastify itself will fail to compile the schema:

{
  response: {
    204: {
      type: 'null',
      description: 'No Content'
    },
    503: {
      type: 'null',
      description: 'Service Unavailable'
    }
  }
}

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 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 different serialization style and explode as specified here.

fastify-swagger supports these options as shown in this example:

fastify.route({
  method: 'GET',
  url: '/',
  schema: {
    querystring: {
      type: 'object',
      required: ['fields'],
      additionalProperties: false,
      properties: {
        fields: {
          type: 'array',
          items: {
            type: 'string'
          },
          minItems: 1,
          //
          // Note that this is an OpenAPI version 2 configuration option. The
          // options changed in version 3.
          //
          // Put `collectionFormat` on the same property which you are defining
          // as an array of values. (i.e. `collectionFormat` should be a sibling
          // of the `type: "array"` specification.)
          collectionFormat: 'multi'
        }
      },
     // OpenAPI 3 serialization options
     explode: false,
     style: "deepObject"
    }
  },
  handler (request, reply) {
    reply.send(request.query.fields)
  }
})

There is a complete runnable example here.

Complex serialization in query and cookie, eg. JSON

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.

fastify.route({
  method: 'GET',
  url: '/',
  schema: {
    querystring: {
      type: 'object',
      required: ['filter'],
      additionalProperties: false,
      properties: {
        filter: {
          type: 'object',
          required: ['foo'],
          properties: {
            foo: { type: 'string' },
            bar: { type: 'string' }
          },
          'x-consume': 'application/json'
        }
      }
    }
  },
  handler (request, reply) {
    reply.send(request.query.filter)
  }
})

Will generate this in the OpenAPI v3 schema's paths:

{
  "/": {
    "get": {
      "parameters": [
        {
          "in": "query",
          "name": "filter",
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "foo"
                ],
                "properties": {
                  "foo": {
                    "type": "string"
                  },
                  "bar": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

Links

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:

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
    200: {
      address: {
        // See the OpenAPI documentation
        operationId: 'getUserAddress',
        parameters: {
          id: '$request.path.id'
        }
      }
    }
  }
}, () => {})

fastify.get('/user/:id/address', {
  schema: {
    operationId: 'getUserAddress',
    params: {
      type: 'object',
      properties: {
        id: {
          type: 'string',
          description: 'the user identifier, as userId'
        }
      },
      required: ['id']
    },
    response: {
      200: {
        type: 'string'
      }
    }
  }
}, () => {})

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.

Protect your documentation routes

You can protect your documentation by configuring an authentication hook. Here is an example using the fastify-basic-auth plugin:

await fastify.register(require('fastify-basic-auth'), {
  validate (username, password, req, reply, done) {
    if (username === 'admin' && password === 'admin') {
      done()
    } else {
      done(new Error('You can not access'))
    }
  },
  authenticate: true
})

fastify.register(fastifySwagger, {
  exposeRoute: true,
  uiHooks: {
    onRequest: fastify.basicAuth
  }
})

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 will return a YAML string.

Integration

You can integration this plugin with fastify-helmet with some little work.

fastify-helmet options example:

.register(helmet, instance => {
  return {
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        "form-action": ["'self'"],
        "img-src": ["'self'", "data:", "validator.swagger.io"],
        "script-src": ["'self'"].concat(instance.swaggerCSP.script),
        "style-src": ["'self'", "https:"].concat(
          instance.swaggerCSP.style
        ),
      }
    }
  }
})

$id and $ref usage

Development

In order to start development run:

npm i
npm run prepare

So that swagger-ui static folder will be generated for you.

How it works under the hood

fastify-static serves swagger-ui static files, then calls /docs/json to get the Swagger file and render it.

How to work with $refs

The /docs/json endpoint in dynamic mode produces a single swagger.json file resolving all your

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.