NestJS course ยท Module 11: Swagger and OpenAPI
Installing and Configuring Swagger in NestJS
In this lesson6
Before our chroniclers begin writing the annals, we must prepare the proper tools - parchment, ink, and imperial seals. In NestJS, this means installing the @nestjs/swagger package and configuring the Swagger module.
Package Installation
The first step is to install the official Swagger package for NestJS:
npm install @nestjs/swaggerThe @nestjs/swagger package contains everything we need: decorators, a configuration module, and Swagger UI integration.
DocumentBuilder - The Architect of Chronicles
DocumentBuilder is a class that allows you to build the API documentation configuration. It works like an architect who designs the structure of our annals:
import { DocumentBuilder } from '@nestjs/swagger';
const config = new DocumentBuilder()
.setTitle('Imperium Romanum API')
.setDescription('API documentation for managing the Roman Empire')
.setVersion('1.0')
.build();DocumentBuilder Methods
| Method | Description | Example |
|---|---|---|
setTitle() | Documentation name | 'Imperium API' |
setDescription() | Project description | 'API for managing legions' |
setVersion() | API version | '1.0', '2.3.1' |
addTag() | Adds a tag (section) | 'Legiones' |
addBearerAuth() | Configures JWT auth | Bearer options |
setContact() | Contact details | Name, URL, email |
setLicense() | API license | Name, URL |
addServer() | API server | URL, description |
build() | Finalizes configuration | Returns OpenAPI object |
SwaggerModule.setup() - Opening the Forum
After building the configuration, we need to "open the Forum" - that is, make the documentation available at a specific URL:
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 1. Build the documentation configuration
const config = new DocumentBuilder()
.setTitle('Imperium Romanum API')
.setDescription('API for managing provinces and legions of the Empire')
.setVersion('1.0')
.addTag('Legiones', 'Legion management')
.addTag('Provinciae', 'Province management')
.addTag('Tributum', 'Tax system')
.addBearerAuth()
.build();
// 2. Create the OpenAPI document
const document = SwaggerModule.createDocument(app, config);
// 3. Serve Swagger UI at the /api/docs path
SwaggerModule.setup('api/docs', app, document);
await app.listen(3000);
}
bootstrap();After starting the application, Swagger UI will be available at http://localhost:3000/api/docs.
SwaggerModule.setup() Parameters
The setup() method accepts four arguments:
- path - the URL path for documentation (e.g.,
'api/docs') - app - the NestJS application instance
- document - the generated OpenAPI document
- options (optional) - additional configuration options
SwaggerModule.setup('api/docs', app, document, {
customSiteTitle: 'Chronicles of the Imperium API',
customfavIcon: '/favicon.ico',
swaggerOptions: {
persistAuthorization: true,
docExpansion: 'none',
filter: true,
},
});Extended DocumentBuilder Configuration
Here is a full configuration example with all options:
const config = new DocumentBuilder()
.setTitle('Imperium Romanum API')
.setDescription('Complete API documentation of the Roman Empire')
.setVersion('2.0')
.setContact('Caesar Augustus', 'https://imperium.rome', 'caesar@rome.gov')
.setLicense('MIT', 'https://opensource.org/licenses/MIT')
.addServer('http://localhost:3000', 'Development server')
.addServer('https://api.imperium.rome', 'Production server')
.addTag('Legiones', 'Legion management endpoints')
.addTag('Provinciae', 'Province management endpoints')
.addBearerAuth(
{ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
'JWT-auth',
)
.build();Practical Exercise
Configure Swagger in the main.ts file of the Imperium project:
Hold on to this rule, young chronicler: DocumentBuilder designs what the annals contain - the title, the version, the tags and the way a caller proves its identity - while SwaggerModule.setup() opens the forum where every legionary can read your API without ever asking you a single question.
Code for this lesson: src/main.ts
// Swagger configuration in main.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
// const app = await NestFactory.create(AppModule);
// TODO: Create the DocumentBuilder configuration
// Use methods: setTitle, setDescription, setVersion, addTag, build
const config = new DocumentBuilder()
.setTitle('Imperium Romanum API')
// TODO: Add the API description
// TODO: Set version to '1.0'
// TODO: Add tag 'Legiones' with a description
// TODO: Add tag 'Provinciae' with a description
.build();
// TODO: Create the OpenAPI document
// const document = SwaggerModule.createDocument(app, config);
// TODO: Expose Swagger UI at the 'api/docs' path
// SwaggerModule.setup('api/docs', app, document);
// await app.listen(3000);
console.log("Swagger UI available at: http://localhost:3000/api/docs");
}
bootstrap();
// Example of a full configuration:
console.log("=== DocumentBuilder ===");
console.log("setTitle() - documentation name");
console.log("setDescription() - project description");
console.log("setVersion() - API version");
console.log("addTag() - section (group of endpoints)");
console.log("addBearerAuth() - JWT configuration");
console.log("build() - finalizes the configuration");
console.log("");
console.log("=== SwaggerModule ===");
console.log("createDocument(app, config) - generates the OpenAPI spec");
console.log("setup(path, app, document) - launches Swagger UI");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which class in @nestjs/swagger is used to build the API documentation configuration?
2. What arguments does the SwaggerModule.setup() method accept in its minimal configuration?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the Swagger configuration in main.ts by adding a description, version, and tags to DocumentBuilder
- Horizontal ordering
Arrange the DocumentBuilder method chain in the correct order:
- Click in order
Arrange the Swagger configuration steps in main.ts in the correct order:
- Code editor
Add @ApiTags('Centuriones') to the controller and @ApiOperation with a summary to the methods