airasoul.

Documenting APIs With Fastify, JSON Schema

Cover Image for Documenting APIs With Fastify, JSON Schema

This is post 2, from a 3 part series, where I will demonstrate how to setup a node.js based api, with an external JSON schema/swagger specification.  I will be using fastify, which supports swagger/json-schema out of the box.

This series of posts contains three entries:

1. Building APIs with Fastify, JSON Schema
2. Documentating APIs with fastify, JSON Schema
3. Testing APis with Fastify, JSON Schema

The source code for this post can be found here:
https://github.com/AndrewKeig/fastify-api-with-json-schema

Here you will find a postman file, to run the endpoints:
https://github.com/AndrewKeig/fastify-api-with-json-schema/blob/master/postman.json

Swagger Setup

We can expose our swagger documentation by configuring fastify-swagger. Full code listing here: src/app/js

We must define our swagger options and register the plugin passing in these options.

  • mode: set this to static as we will be using an external static swagger file
  • exposeRoute: option to expose the swagger documentation
  • path: the imported swagger document
  • postProcessor: we run this function to change the host and schemes, so you can set these for different environments.
const swaggerOptions = {
  mode:  'static',
  exposeRoute: true,
  specification: {
     path: specification,
     postProcessor: swaggerObject => {
      const swagger = {
        ...swaggerObject,
        host:'localhost:3000',
        schemes: ['http'];
      };
     return swagger;
    },
  },
};

app.register(require('fastify-swagger'), swaggerOptions);

We have successfully exposed the swagger documentation; now when you start the fastify server you can see the swagger documentation by visiting:

http://localhost:3000/documentation