Swagger / OpenAPI From Schemas

Free Docs From the Schemas You Already Wrote

Swagger / OpenAPI From Schemas

@fastify/swagger reads your route schemas and exposes a live OpenAPI 3 document; pair it with @fastify/swagger-ui for an interactive browser.

4 min read Level 2/5 #fastify#swagger#openapi
What you'll learn
  • Install @fastify/swagger and @fastify/swagger-ui
  • Register them at boot
  • Visit /docs to explore the API

You wrote schemas anyway. Tell Fastify to publish them as OpenAPI 3 and you get free interactive docs and a contract clients can codegen against.

Install

npm i @fastify/swagger @fastify/swagger-ui

Register

import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';

await app.register(fastifySwagger, {
  openapi: {
    info: {
      title: 'JS Schools API',
      description: 'Public API for JS Schools',
      version: '1.0.0',
    },
    servers: [{ url: 'https://api.jsschools.com' }],
    components: {
      securitySchemes: {
        bearerAuth: { type: 'http', scheme: 'bearer' },
      },
    },
  },
});

await app.register(fastifySwaggerUi, {
  routePrefix: '/docs',
  uiConfig: { docExpansion: 'list' },
});

Boot the server and visit http://localhost:3000/docs — every route with a schema appears, groupable by tag, with a built-in “Try it out” button.

Tagging Routes

app.post('/posts', {
  schema: {
    tags: ['posts'],
    summary: 'Create a new post',
    description: 'Creates a draft post owned by the authenticated user.',
    security: [{ bearerAuth: [] }],
    body: PostBody,
    response: { 201: PostReply },
  },
  handler: createPost,
});

tags, summary, description, and security are passed straight through to the OpenAPI document.

Exporting the Spec

For codegen pipelines, dump the spec at build time with app.swagger() — write the JSON to a file and feed it to openapi-typescript, orval, or Stoplight.

Plugins — Fastify's Composition Unit →