When building APIs, documentation is not optionalβitβs essential. Without it, frontend developers, QA engineers, and even your future self will struggle to understand how your system works.
Thatβs where the Swagger Module comes in.
Using:
NestJS can automatically generate interactive API documentation based entirely on your code.
The Swagger Module is a tool that:
π In simple terms:
Swagger Module = Auto-generated, interactive API documentation
After setup, youβll have a UI like:
http://localhost:3000/docs
Where you can:
npm install @nestjs/swagger swagger-ui-express
main.tsimport { NestFactory } from '@nestjs/core';import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';import { AppModule } from './app.module';async function bootstrap() {const app = await NestFactory.create(AppModule);const config = new DocumentBuilder().setTitle('My API').setDescription('API documentation').setVersion('1.0').addBearerAuth().build();const document = SwaggerModule.createDocument(app, config);SwaggerModule.setup('docs', app, document);await app.listen(3000);}bootstrap();
Define how your request body looks using DTOs:
import { ApiProperty } from '@nestjs/swagger';export class CreateUserDto {@ApiProperty({ example: 'john_doe' })username: string;@ApiProperty({ example: 'john@gmail.com' })email: string;}
π This tells Swagger:
Provide realistic API responses:
import { ApiResponse } from '@nestjs/swagger';@ApiResponse({status: 201,description: 'User created successfully',schema: {example: {id: 1,username: 'john_doe',email: 'john@gmail.com',},},})
π Helps frontend developers understand real output instantly.
Organize endpoints into categories:
import { ApiTags } from '@nestjs/swagger';@ApiTags('Users')@Controller('users')export class UserController {}
π Swagger UI will group endpoints under Users
Instead of writing many decorators, enable the plugin:
{"compilerOptions": {"plugins": [{"name": "@nestjs/swagger/plugin","options": {"classValidatorShim": true,"introspectComments": true}}]}}
@ApiProperty()Never expose raw entities directly.
Good docs = faster development
Keep Swagger clean and readable
import { IsEmail } from 'class-validator';export class CreateUserDto {username: string;@IsEmail()email: string;}
π Swagger + validation = strong API contract
Example:
{"success": true,"data": {},"message": "OK"}
npm install @nestjs/swagger/plugin
π Wrong β plugin is built-in
π Makes API hard to use
π Leads to confusing documentation
ts-node without buildπ Plugin wonβt work
src/βββ config/β βββ swagger.config.tsβββ modules/β βββ user/β βββ dto/β βββ user.controller.tsβ βββ user.service.ts
Swagger Module is not just a documentation toolβitβs a core part of modern backend development.
It helps you:
If your API is hard to understand in Swagger, your API design probably needs improvement.
If you want to go further, next topics to explore: