Skip to main content

NestJS Swagger Documentation: Auto-Generate API Docs Easily

Sakar Khadka
8 min read
NestJS Swagger Documentation: Auto-Generate API Docs Easily

What is Swagger in NestJS?#

Swagger is a powerful tool that helps developers design, document, and test RESTful APIs in a simple and interactive way. It follows the OpenAPI Specification, which standardizes how APIs are described so both humans and machines can understand them easily.

How Swagger Docs Works In Project#

Swagger scans your backend code and generates documentation using metadata such as:

  • Route definitions (@Controller, @Get, @Post)
  • Data validation (class-validator)
  • DTOs (Data Transfer Objects)
  • Custom decorators like @ApiProperty, @ApiTags, etc.

Once configured, it provides a UI dashboard (usually at /api or /docs) where all endpoints are displayed in a structured format.

Key Benefits of Swagger in Real Projects#

  • Automatic API Documentation
  • Built-in API Testing (No Postman Needed)
  • Better Team Collaboration
  • Improves Developer Experience (DX)
  • Faster Development & Debugging Etc.

NestJS Swagger Setup Guide (Step-by-Step)#

Swagger Setup for automatically generate API documentation in your NestJS application. In this guide, you’ll learn how to set up Swagger properly and use it in a clean, scalable, production-ready way.

Step: 1 ~ Install Required Packages#

npm install @nestjs/swagger swagger-ui-express

Step: 2 ~ Configure Swagger On main.ts#

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
 
  // Intregrate Swagger Docs
  const config = new DocumentBuilder()
    .setTitle('Sakar API Docs')
    .setDescription('API Docs For Testing Sakar')
    .setVersion('1.0')
    .addTag('sakar')
    .build();
 
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document); //Setup Swagger Docs
 
  await app.listen(process.env.PORT ?? 4000);
}
bootstrap();

Step: 3 ~ Add Swagger Annotations to your controller & DTOs#

import { Controller, Get, Post, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
 
@ApiTags('Users')
@Controller('users')
export class UsersController {
 
  @Get()
  @ApiOperation({ summary: 'Get all users' })
  @ApiResponse({ status: 200, description: 'Users fetched successfully' })
  getUsers() {
    return [];
  }
 
  @Post()
  @ApiOperation({ summary: 'Create a new user' })
  createUser(@Body() body: any) {
    return body;
  }
}

Use DTOs for Better Documentation#

import { ApiProperty } from '@nestjs/swagger';
 
export class CreateUserDto {
  @ApiProperty({ example: 'Sakar Khadka' })
  name: string;
 
  @ApiProperty({ example: '[email protected]' })
  email: string;
}

Step: 4 ~ Run the application#

npm run start