@fastify/swagger vs @loopback/openapi-v3 vs swagger-jsdoc
Generating OpenAPI Specifications in Node.js Applications
@fastify/swagger@loopback/openapi-v3swagger-jsdocSimilar Packages:

Generating OpenAPI Specifications in Node.js Applications

@fastify/swagger, @loopback/openapi-v3, and swagger-jsdoc are tools designed to generate OpenAPI (Swagger) documentation for Node.js APIs, but they serve different architectural patterns. @fastify/swagger is a plugin specifically built for the Fastify framework, leveraging its schema compilation engine to auto-generate specs from route definitions. @loopback/openapi-v3 is an integral part of the LoopBack 4 framework, tightly coupling API documentation with its strong typing system and decorators. swagger-jsdoc is a framework-agnostic utility that parses JSDoc comments in your code to produce a specification file, working with Express, Hapi, or any other server library.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
@fastify/swagger01,095356 kB162 months agoMIT
@loopback/openapi-v305,107255 kB336a month agoMIT
swagger-jsdoc01,789710 kB474 months agoMIT

Generating OpenAPI Specs: Fastify Plugin vs LoopBack Core vs JSDoc Parser

Generating accurate API documentation is critical for frontend teams to integrate reliably with backend services. The three tools — @fastify/swagger, @loopback/openapi-v3, and swagger-jsdoc — solve this problem in fundamentally different ways. One relies on framework internals, one on TypeScript decorators, and one on code comments. Let's break down how they work in real engineering scenarios.

âš™ī¸ How Specifications Are Generated

@fastify/swagger hooks directly into Fastify's routing and schema system.

  • You define validation schemas for your routes using JSON Schema.
  • The plugin automatically reads these schemas and builds the OpenAPI document.
  • No extra comments or decorators are needed; the code defines the contract.
// fastify app with @fastify/swagger
const fastify = require('fastify')();
await fastify.register(require('@fastify/swagger'));

fastify.get('/users', {
  schema: {
    response: {
      200: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            id: { type: 'number' },
            name: { type: 'string' }
          }
        }
      }
    }
  }
}, async (request, reply) => {
  return [{ id: 1, name: 'Alice' }];
});

// The spec is auto-generated from the 'schema' property above

@loopback/openapi-v3 uses TypeScript decorators to annotate controllers.

  • You decorate methods with @get, @post, etc., and define response types.
  • The framework scans these decorators at startup to build the spec.
  • This enforces a strict structure where documentation is part of the class definition.
// loopback controller with @loopback/openapi-v3
import {get, param, ResponseObject} from '@loopback/rest';

const UserResponse: ResponseObject = {
  description: 'User response',
  content: {'application/json': {schema: {type: 'array', items: {$ref: '#/components/schemas/User'}}}},
};

export class UserController {
  @get('/users', {
    responses: {
      '200': UserResponse,
    },
  })
  async find(): Promise<object[]> {
    return [{id: 1, name: 'Alice'}];
  }
}

swagger-jsdoc parses special comments (JSDoc) in your source files.

  • You write YAML or JSON inside comment blocks above your route handlers.
  • The tool scans your files, extracts these blocks, and compiles them into a spec.
  • It works with any framework because it ignores the actual code logic and only reads comments.
// express app with swagger-jsdoc
/**
 * @swagger
 * /users:
 *   get:
 *     summary: Returns a list of users
 *     responses:
 *       200:
 *         description: A list of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   id:
 *                     type: number
 *                   name:
 *                     type: string
 */
app.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'Alice' }]);
});

🔄 Syncing Docs with Code Logic

Keeping documentation in sync with actual behavior is the hardest part of API maintenance.

@fastify/swagger guarantees sync because it uses the same schema for validation and docs.

  • If you change the validation rule, the documentation updates instantly.
  • You cannot have a mismatch between what the API accepts and what the docs say.
  • This reduces the risk of frontend developers sending invalid data based on outdated docs.
// Change the schema here...
fastify.get('/users', {
  schema: {
    response: {
      200: {
        type: 'array',
        items: { type: 'object', properties: { id: { type: 'string' } } } // Changed id to string
      }
    }
  }
}, handler);
// ...and the Swagger UI reflects the change immediately without touching docs

@loopback/openapi-v3 keeps sync through TypeScript types and decorators.

  • Since the decorators often reference shared type definitions, refactoring types updates the spec.
  • However, if you manually write a decorator response that doesn't match the return type, you can create drift.
  • It relies on the developer to keep the decorator arguments consistent with the method implementation.
// If you change the return type of the method but forget the decorator:
async find(): Promise<object[]> { /* ... */ } 
// The decorator still defines the old response structure unless updated manually

swagger-jsdoc is prone to drift because comments are decoupled from logic.

  • You can change the code logic entirely without updating the comment block.
  • The tool has no way to know if the comment matches the actual response.
  • Teams must enforce strict code review rules to ensure comments are updated with every change.
// Code returns a string, but comment says number
app.get('/count', (req, res) => {
  res.send('10'); // Actual output
});
// @swagger block still describes 'type: number' -> MISMATCH

🧩 Framework Integration and Setup

How deeply the tool integrates with your server framework dictates your setup complexity.

@fastify/swagger is a first-class citizen of Fastify.

  • Installation is a single register call.
  • It inherits Fastify's configuration for logging, prefixes, and UI rendering.
  • It supports serving the UI at a custom route with minimal config.
await fastify.register(require('@fastify/swagger'), {
  routePrefix: '/documentation',
  swagger: {
    info: { title: 'My API', version: '1.0.0' }
  },
  exposeRoute: true
});

@loopback/openapi-v3 is baked into the LoopBack 4 core.

  • There is no separate installation step; it comes with the framework.
  • Configuration is handled in the application's main file via the openapiSpec property.
  • It assumes you are following the LoopBack controller/repository pattern.
// In application.ts
this.projectRoot = __dirname;
this.bind(RestApplicationBindings.OPENAPI_SPEC).to({
  // Custom spec configuration if needed
});

swagger-jsdoc requires manual wiring regardless of your framework.

  • You must define options pointing to your source files and a base swagger definition.
  • You need to manually attach the generated spec to your server's routing logic.
  • It often requires a separate middleware to serve the UI (like swagger-ui-express).
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const options = {
  definition: { openapi: '3.0.0', info: { title: 'My API', version: '1.0.0' } },
  apis: ['./routes/*.js'], // Path to files with comments
};

const swaggerSpec = swaggerJsdoc(options);
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

đŸ› ī¸ Customization and Advanced Features

Real-world APIs often need complex documentation features like authentication schemes or custom tags.

@fastify/swagger allows transformation hooks to modify the spec before serving.

  • You can use the transform option to inject security definitions or group endpoints.
  • It supports referencing external JSON schema files for complex models.
  • This is powerful for large systems where the base spec needs dynamic adjustment.
await fastify.register(require('@fastify/swagger'), {
  transform: (spec) => {
    spec.security = [{ apiKey: [] }];
    return spec;
  }
});

@loopback/openapi-v3 provides decorators for almost every OpenAPI field.

  • You can add tags, security requirements, and parameter descriptions directly on methods.
  • It supports binding custom components to the spec via the dependency injection system.
  • This granular control is useful but can make controller files verbose.
@authenticate('jwt')
@get('/protected', {
  security: [{ 'jwt': [] }],
  tags: ['Secure']
})
async protectedMethod() { /* ... */ }

swagger-jsdoc relies on the richness of your JSDoc comments.

  • You must write valid YAML inside comments to define security or tags.
  • There is no programmatic way to inject data; everything must be in the text block.
  • This makes refactoring difficult, as changing a tag name requires finding and editing text in comments.
/**
 * @swagger
 * security:
 *   - bearerAuth: []
 * tags:
 *   - Secure
 */

🌱 When Not to Use These

Selecting the wrong tool can create unnecessary technical debt.

  • Avoid @fastify/swagger if you are not using Fastify. It is incompatible with Express or Koa without significant hacking.
  • Avoid @loopback/openapi-v3 if you are not building a full LoopBack 4 application. It is not a standalone library.
  • Avoid swagger-jsdoc if your team struggles with discipline in maintaining comments. The drift between code and docs will become unmanageable in large projects.

📌 Summary Table

Feature@fastify/swagger@loopback/openapi-v3swagger-jsdoc
Primary SourceJSON SchemasTypeScript DecoratorsJSDoc Comments
FrameworkFastify OnlyLoopBack 4 OnlyAny (Express, Hapi, etc.)
Sync ReliabilityHigh (Auto)Medium (Type-assisted)Low (Manual)
Setup EffortLowLow (if using LB4)Medium
VerbosityLowMediumHigh

💡 Final Recommendation

Think about where your "source of truth" lives.

  • If you use Fastify: @fastify/swagger is the clear winner. It turns your validation schemas into docs automatically, removing the human error factor.
  • If you use LoopBack 4: @loopback/openapi-v3 is your only logical choice. It is deeply integrated and leverages your existing TypeScript types.
  • If you use Express or others: swagger-jsdoc is the standard option, but be prepared to enforce strict code review processes to keep comments accurate. Alternatively, consider looking into newer tools that generate specs from TypeScript types directly if your project is heavily typed.

Final Thought: The best documentation is the one you don't have to think about. Tools that generate specs from code logic (like Fastify's schemas) are superior to tools that rely on manual comments, as they ensure your frontend team always sees the reality of your API.

How to Choose: @fastify/swagger vs @loopback/openapi-v3 vs swagger-jsdoc

  • @fastify/swagger:

    Choose @fastify/swagger if your backend is built on Fastify and you want zero-effort documentation generation. It reads the JSON schemas you already define for validation and instantly converts them into an OpenAPI spec, ensuring your docs never drift from your actual validation logic. This is the best choice for teams prioritizing performance and schema-first development within the Fastify ecosystem.

  • @loopback/openapi-v3:

    Choose @loopback/openapi-v3 if you are building your application with the LoopBack 4 framework. It is not a standalone tool but a core feature that uses TypeScript decorators to define endpoints, making it ideal for projects that require strong typing, dependency injection, and a highly opinionated architecture. Do not select this if you are using a different framework, as it requires the full LoopBack runtime.

  • swagger-jsdoc:

    Choose swagger-jsdoc if you use Express, Hapi, or a custom server and prefer keeping documentation close to your route handlers via comments. It is the right fit for teams that want framework independence and don't mind maintaining large JSDoc blocks to keep their specs accurate. Avoid this if you want automatic synchronization between validation logic and documentation, as it relies entirely on manual comment updates.

README for @fastify/swagger

@fastify/swagger

NPM version CI neostandard javascript style

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 versionFastify 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:

const fastify = require('fastify')()

await fastify.register(require('@fastify/swagger'), {
  openapi: {
    openapi: '3.0.0',
    info: {
      title: 'Test swagger',
      description: 'Testing the Fastify swagger API',
      version: '0.1.0'
    },
    servers: [
      {
        url: 'http://localhost:3000',
        description: 'Development server'
      }
    ],
    tags: [
      { name: 'user', description: 'User related end-points' },
      { name: 'code', description: 'Code related end-points' }
    ],
    components: {
      securitySchemes: {
        apiKey: {
          type: 'apiKey',
          name: 'apiKey',
          in: 'header'
        }
      }
    },
    externalDocs: {
      url: 'https://swagger.io',
      description: 'Find more info here'
    }
  }
})

fastify.put('/some-route/:id', {
  schema: {
    description: 'post some data',
    tags: ['user', 'code'],
    summary: 'qwerty',
    security: [{ apiKey: [] }],
    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' }
        }
      }
    }
  }
}, (req, reply) => { })

await fastify.ready()
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:

const fastify = require('fastify')()
const fastify = fastify()
await fastify.register(require('@fastify/swagger'))
fastify.register(require("@fastify/autoload"), {
  dir: path.join(__dirname, 'routes')
})
await fastify.ready()
fastify.swagger()

API

Register options

Modes

@fastify/swagger supports dynamic and static registration modes:

Dynamic

dynamic is the default mode, which auto-generates API schemas 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 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.

Examples of using @fastify/swagger in dynamic mode:

Static

static mode must be configured explicitly. It serves an existing Swagger or OpenAPI schema passed to 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 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

OptionDefaultDescription
hiddenTagX-HIDDENTag to control hiding of routes.
hideUntaggedfalseIf true remove routes without tags from resulting Swagger/OpenAPI schema file.
openapi{}OpenAPI configuration.
stripBasePathtrueStrips base path from routes in docs.
swagger{}Swagger configuration.
transformnullTransform method for the route's schema and url. documentation.
transformObjectnullTransform method for the swagger or openapi object before it is rendered. documentation.
refResolver{}Option to manage the $refs of the application's schemas. Read the $ref documentation
exposeHeadRoutesfalseInclude HEAD routes in the definitions
decorator'swagger'Overrides the Fastify decorator. documentation.
convertConstToEnumtrueConverts const properties to single-value enums. Support for const was only added in OpenAPI Schema 3.1.0.

Transform

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 (body) transformedSchema.body = convert(body)
    if (querystring) transformedSchema.querystring = convert(querystring)
    if (headers) transformedSchema.headers = convert(headers)
    if (response) transformedSchema.response = convert(response)

    // can add the hide tag if needed
    if (url.startsWith('/internal')) transformedSchema.hide = true

    // can transform the url
    if (url.startsWith('/latest_version/endpoint')) transformedUrl = url.replace('latest_version', 'v3')

    // can add the hide tag for routes that do not match the swaggerObject version
    if (route?.constraints?.version !== swaggerObject.swagger) transformedSchema.hide = true

    return { schema: transformedSchema, url: transformedUrl }
  }
})

The transform function can also be attached to a specific endpoint:

fastify.get("/", {
  schema: { ... },
  config: {
    swaggerTransform: ({ schema, url, route, swaggerObject }) => { ... }
  }
})

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.

await fastify.register(require('@fastify/swagger'), {
  swagger: { ... },
  transformObject ({ swaggerObject }) => {
    swaggerObject.info.title = 'Transformed';
    return swaggerObject;
  }
})

Managing your $refs

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:

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

For details on buildLocalReference arguments, see the documentation.

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:

// Create an internal Swagger doc
await fastify.register(require('@fastify/swagger'), {
  swagger: { ... },
  transform: ({ schema, url, route, swaggerObject }) => {
    const {
      params,
      body,
      querystring,
      headers,
      response,
      ...transformedSchema
    } = schema
    let transformedUrl = URL

    // Hide external URLs
    if (url.startsWith('/external')) transformedSchema.hide = true

    return { schema: transformedSchema, url: transformedUrl }
  },
  decorator: 'internalSwagger'
})

// Create an external Swagger doc
await fastify.register(require('@fastify/swagger'), {
  swagger: { ... },
  transform: ({ schema, url, route, swaggerObject }) => {
    const {
      params,
      body,
      querystring,
      headers,
      response,
      ...transformedSchema
    } = schema
    let transformedUrl = URL

    // Hide internal URLs
    if (url.startsWith('/internal')) transformedSchema.hide = true

    return { schema: transformedSchema, url: transformedUrl }
  },
  decorator: 'externalSwagger'
})

Then call those decorators individually to retrieve them:

fastify.internalSwagger()
fastify.externalSwagger()

Route options

HEAD routes can be included in the definitions by adding exposeHeadRoute in the route config:

  fastify.get('/with-head', {
    schema: {
      operationId: 'with-head',
      response: {
        200: {
          description: 'Expected Response',
          type: 'object',
          properties: {
            foo: { type: 'string' }
          }
        }
      }
    },
    config: {
      swagger: {
        exposeHeadRoute: true,
      }
    }
  }, () => {})

Response Options

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:

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 an 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"
              }
            }
          }
        }
      }
    }
  }
}

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'
      }
    }
  }
}, () => {})

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.

Example:

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

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

Response headers

Response headers can be decorated with the following example. Specify the type property when decorating response headers to prevent schema modification by Fastify.

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

Different content types responses

â„šī¸ Note: Supported only by OpenAPI v3, not Swagger (OpenAPI v2).

Different content types are supported by @fastify/swagger and @fastify. Use content for the response to prevent Fastify from failing to compile the schema:

{
  response: {
    200: {
      description: 'Description and all status-code based properties are working',
      content: {
        'application/json': {
          schema: {
            name: { type: 'string' },
            image: { type: 'string' },
            address: { type: 'string' }
          }
        },
        'application/vnd.v1+json': {
          schema: {
            fullName: { type: 'string' },
            phone: { type: 'string' }
          }
        }
      }
    }
  }
}
Empty Body Responses

Empty body responses are supported by @fastify/swagger. Specify type: 'null' for the response to prevent Fastify from failing 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 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 instance
const 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: 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: Supported only by OpenAPI v3, not Swagger (OpenAPI v2).

http://localhost/?filter={"foo":"baz","bar":"qux"}

â„šī¸ Note: Change Fastify's default query string parser to produce a JavaScript object conforming 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)
  }
})

Generates 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"
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}
Route parameters

Route parameters in Fastify are called params. These are values included in the URL of the requests, for example:

fastify.route({
  method: 'GET',
  url: '/:id',
  schema: {
    params: {
      type: 'object',
      properties: {
        id: {
          type: 'string',
          description: 'user id'
        }
      }
    }
  },
  handler (request, reply) {
    reply.send(request.params.id)
  }
})

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

{
  "/{id}": {
    "get": {
      "parameters": [
        {
          "type": "string",
          "description": "user id",
          "required": true,
          "in": "path",
          "name": "id"
        }
      ],
      "responses": {
        "200": {
          "description": "Default Response"
        }
      }
    }
  }
}

Generates this in the OpenAPI v3 schema's paths:

{
  "/{id}": {
    "get": {
      "parameters": [
        {
          "schema": {
            "type": "string"
          },
          "in": "path",
          "name": "id",
          "required": true,
          "description": "user id"
        }
      ],
      "responses": {
        "200": {
          "description": "Default Response"
        }
      }
    }
  }
}

When params is not present in the schema, or a schema is not provided, parameters are automatically generated:

fastify.route({
  method: 'POST',
  url: '/:id',
  handler (request, reply) {
    reply.send(request.params.id)
  }
})

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

{
  "/{id}": {
    "get": {
      "parameters": [
        {
          "type": "string",
          "required": true,
          "in": "path",
          "name": "id"
        }
      ],
      "responses": {
        "200": {
          "description": "Default Response"
        }
      }
    }
  }
}

Generates this in the OpenAPI v3 schema's paths:

{
  "/{id}": {
    "get": {
      "parameters": [
        {
          "schema": {
            "type": "string"
          },
          "in": "path",
          "name": "id",
          "required": true
        }
      ],
      "responses": {
        "200": {
          "description": "Default Response"
        }
      }
    }
  }
}

Links

â„šī¸ Note: Supported only by OpenAPI v3, not Swagger (OpenAPI v2).

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
    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.

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:

.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
        ),
      }
    }
  }
})

Add examples to the schema

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...):

fastify.route({
  method: 'POST',
  url: '/',
  schema: {
    querystring: {
      type: 'object',
      required: ['filter'],
      properties: {
        filter: {
          type: 'object',
          required: ['foo'],
          properties: {
            foo: { type: 'string' },
            bar: { type: 'string' }
          },
          examples: [
            { foo: 'bar', bar: 'baz' },
            { foo: 'foo', bar: 'bar' }
          ]
        }
      },
      examples: [
        { filter: { foo: 'bar', bar: 'baz' } }
      ]
    }
  },
  handler (request, reply) {
    reply.send(request.query.filter)
  }
})

Generates this in the OpenAPI v3 schema's paths:

"/": {
  "post": {
    "requestBody": {
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "required": ["filter"],
            "properties": {
              "filter": {
                "type": "object",
                "required": ["foo"],
                "properties": {
                  "foo": { "type": "string" },
                  "bar": { "type": "string" }
                },
                "example": { "foo": "bar", "bar": "baz" }
              }
            }
          },
          "examples": {
            "example1": {
              "value": { "filter": { "foo": "bar", "bar": "baz" } }
            },
            "example2": {
              "value": { "filter": { "foo": "foo", "bar": "bar" } }
            }
          }
        }
      },
      "required": true
    },
    "responses": { "200": { "description": "Default Response" } }
  }
}

Use the x-examples field to set names or add descriptions to schema examples in OpenAPI format:

// Need to add a new allowed keyword to ajv in fastify instance
const fastify = Fastify({
  ajv: {
    plugins: [
      function (ajv) {
        ajv.addKeyword({ keyword: 'x-examples' })
      }
    ]
  }
})

fastify.route({
  method: 'POST',
  url: '/feed-animals',
  schema: {
    body: {
      type: 'object',
      required: ['animals'],
      properties: {
        animals: {
          type: 'array',
          items: {
            type: 'string'
          },
          minItems: 1,
        }
      },
      "x-examples": {
        Cats: {
          summary: "Feed cats",
          description:
            "A longer **description** of the options with cats",
          value: {
            animals: ["Tom", "Garfield", "Felix"]
          }
        },
        Dogs: {
          summary: "Feed dogs",
          value: {
            animals: ["Spike", "Odie", "Snoopy"]
          }
        }
      }
    }
  },
  handler (request, reply) {
    reply.send(request.body.animals)
  }
})

$id and $ref usage

How to work with $refs

The /docs/json endpoint in dynamic mode produces a single swagger.json file, resolving all of the references.

Acknowledgments

This project is kindly sponsored by:

Past sponsors:

  • LetzDoIt

License

Licensed under MIT.