Home
NestJS
NestJS - Swagger Module
September 06, 2023
1 min

πŸš€ Swagger Module in NestJS β€” Complete Practical Guide

🧠 Introduction

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/swagger

NestJS can automatically generate interactive API documentation based entirely on your code.


πŸ“˜ What is Swagger Module?

The Swagger Module is a tool that:

  • Scans your NestJS application
  • Generates an OpenAPI Specification (JSON)
  • Displays it using a beautiful interactive UI

πŸ‘‰ In simple terms:

Swagger Module = Auto-generated, interactive API documentation


πŸ–₯️ What You Get

After setup, you’ll have a UI like:

http://localhost:3000/docs

Where you can:

  • View all endpoints
  • See request/response schemas
  • Try APIs directly in the browser

βš™οΈ Setup Swagger in NestJS

1. Install dependencies

npm install @nestjs/swagger swagger-ui-express

2. Configure in main.ts

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);
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();

🧱 Core Concepts

1. Decorating Model Properties

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:

  • Field names
  • Data types
  • Example values

2. Adding Example Responses

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.


3. Using Tags to Group APIs

Organize endpoints into categories:

import { ApiTags } from '@nestjs/swagger';
@ApiTags('Users')
@Controller('users')
export class UserController {}

πŸ‘‰ Swagger UI will group endpoints under Users


⚑ Swagger CLI Plugin (Important)

Instead of writing many decorators, enable the plugin:

{
"compilerOptions": {
"plugins": [
{
"name": "@nestjs/swagger/plugin",
"options": {
"classValidatorShim": true,
"introspectComments": true
}
}
]
}
}

Benefits:

  • Auto-generate @ApiProperty()
  • Use TypeScript types directly
  • Reduce boilerplate

🧠 Best Practices

βœ… 1. Always Use DTOs

Never expose raw entities directly.


βœ… 2. Add Examples

Good docs = faster development


βœ… 3. Group APIs with Tags

Keep Swagger clean and readable


βœ… 4. Combine with Validation

import { IsEmail } from 'class-validator';
export class CreateUserDto {
username: string;
@IsEmail()
email: string;
}

πŸ‘‰ Swagger + validation = strong API contract


βœ… 5. Standardize Responses

Example:

{
"success": true,
"data": {},
"message": "OK"
}

⚠️ Common Mistakes

❌ Installing plugin separately

npm install @nestjs/swagger/plugin

πŸ‘‰ Wrong β€” plugin is built-in


❌ No examples in responses

πŸ‘‰ Makes API hard to use


❌ Messy tags

πŸ‘‰ Leads to confusing documentation


❌ Using ts-node without build

πŸ‘‰ Plugin won’t work


πŸ—οΈ Suggested Project Structure

src/
β”œβ”€β”€ config/
β”‚ └── swagger.config.ts
β”œβ”€β”€ modules/
β”‚ └── user/
β”‚ β”œβ”€β”€ dto/
β”‚ β”œβ”€β”€ user.controller.ts
β”‚ └── user.service.ts

🎯 Conclusion

Swagger Module is not just a documentation toolβ€”it’s a core part of modern backend development.

It helps you:

  • Build self-documented APIs
  • Improve team collaboration
  • Reduce communication overhead
  • Deliver faster and cleaner systems

🧩 Final Thought

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:

  • Pagination + Swagger
  • Authentication (JWT) in Swagger UI
  • Generic API response wrappers
  • Versioning APIs (v1, v2)


Tags

#NestJS

Share

Related Posts

NextJS
NestJS - Setup with PostgreSQL & Docker
September 06, 2023
1 min
Β© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube