NestJS

API & Swagger

Building REST APIs and documenting them automatically using Swagger.

Swagger Setup: Bootstrapping Swagger module in the main entry file to auto-generate documentation.
📄main.ts
typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Configure Swagger Document Builder
  const config = new DocumentBuilder()
    .setTitle('User Management API')
    .setDescription('The API description for the User Management system.')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document); // Setup UI at /api/docs

  await app.listen(3000);
}
bootstrap();
API Controller: Using NestJS decorators and Swagger annotations for endpoint documentation.
📄users.controller.ts
typescript
import { Controller, Get, Post, Body, Param, Put, Delete } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';
import { CreateUserDto } from './dto/create-user.dto';

@ApiTags('users')
@Controller('users')
export class UsersController {
  
  @Get()
  @ApiOperation({ summary: 'Get all users' })
  @ApiResponse({ status: 200, description: 'Return all users.' })
  findAll() {
    return [{ id: 1, name: 'John Doe', email: 'john@example.com' }];
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get a user by ID' })
  @ApiParam({ name: 'id', required: true, description: 'User ID' })
  @ApiResponse({ status: 200, description: 'Return the user data.' })
  @ApiResponse({ status: 404, description: 'User not found.' })
  findOne(@Param('id') id: string) {
    return { id: Number(id), name: 'John Doe', email: 'john@example.com' };
  }

  @Post()
  @ApiOperation({ summary: 'Create a new user' })
  @ApiResponse({ status: 201, description: 'The user has been successfully created.' })
  create(@Body() createUserDto: CreateUserDto) {
    return { id: 2, ...createUserDto };
  }
}