Swagger helps you create clear and easy-to-read API docs automatically. It shows what your API can do and how to use it.
0
0
Swagger API documentation in NestJS
Introduction
You want to share your API with other developers clearly.
You need a simple way to test your API endpoints.
You want to keep your API docs updated automatically as you change code.
You want to generate client code or SDKs from your API docs.
You want to improve communication between frontend and backend teams.
Syntax
NestJS
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; const config = new DocumentBuilder() .setTitle('API Title') .setDescription('API description') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document);
Use DocumentBuilder to set your API info like title and version.
Call SwaggerModule.setup() to serve the docs at a URL (e.g., '/api').
Examples
Basic setup with title, description, and version.
NestJS
const config = new DocumentBuilder() .setTitle('My App API') .setDescription('API for my app') .setVersion('0.1') .build();
Adds support for Bearer token authentication in the docs.
NestJS
const config = new DocumentBuilder() .addBearerAuth() .setTitle('Secure API') .setVersion('1.0') .build();
Serve the Swagger UI at the '/docs' path.
NestJS
SwaggerModule.setup('docs', app, document);Sample Program
This example creates a NestJS app and sets up Swagger docs at /api. When you run it, you can open the URL to see interactive API docs.
NestJS
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); const config = new DocumentBuilder() .setTitle('Cats API') .setDescription('API to manage cats') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); console.log('API docs available at http://localhost:3000/api'); } bootstrap();
OutputSuccess
Important Notes
Remember to decorate your controllers and DTOs with Swagger decorators like @ApiTags() and @ApiProperty() to improve docs.
Swagger UI is interactive, so you can test API calls directly from the browser.
Keep your API docs updated by running the app after code changes.
Summary
Swagger auto-generates API docs that are easy to read and test.
Use DocumentBuilder to configure your API info.
Serve docs with SwaggerModule.setup() at a chosen URL.