Understand registration modes: Dynamic vs Static
mainWhen registering @fastify/swagger, you can choose between two modes:
- Dynamic (Default): Automatically generates API schemas from your Fastify route schemas. You can configure the output to be either Swagger (OpenAPI v2) using the
swaggeroption or OpenAPI v3 using theopenapioption. - Static: Serves an existing Swagger or OpenAPI schema file. You must provide the file path via
specification.path.
Use Dynamic mode for most use cases where you want your documentation to stay in sync with your code automatically. Use Static mode if you already have a standalone specification file.
// Dynamic mode (default)
await fastify.register(require('@fastify/swagger'), {
swagger: { info: { title: 'My API', version: '1.0.0' } }
});
// Static mode
await fastify.register(require('@fastify/swagger'), {
mode: 'static',
specification: {
path: './path/to/spec.yaml',
baseDir: '/absolute/path/to/specs'
}
});