NestJS course · Module 11: Swagger and OpenAPI

Main Project: Complete Imperium API Documentation

3 min read ·
In this lesson3

The time has come for the grand opus - creating the complete Chronicles of the Empire! In this project, you will combine all the knowledge from this module to create a fully documented API for managing the Roman Empire.

Project Requirements

Your Chronicles of the Empire must include:

1. Swagger Configuration in main.ts

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';

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

  app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));

  const config = new DocumentBuilder()
    .setTitle('Imperium Romanum API')
    .setDescription('Complete API documentation for managing the Roman Empire')
    .setVersion('1.0')
    .addTag('Legiones', 'Managing legions and soldiers')
    .addTag('Provinciae', 'Managing provinces of the Empire')
    .addTag('Tributum', 'Tax system and treasury')
    .addBearerAuth(
      { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
      'JWT-auth',
    )
    .setContact('Consul Maximus', 'https://imperium.rome', 'consul@rome.gov')
    .setLicense('Lex Romana', 'https://imperium.rome/lex')
    .build();

  const document = SwaggerModule.createDocument(app, config);

  SwaggerModule.setup('api/docs', app, document, {
    customSiteTitle: 'Chronicles of the Imperium API',
    swaggerOptions: {
      persistAuthorization: true,
      filter: true,
      showRequestDuration: true,
    },
  });

  await app.listen(3000);
}
bootstrap();

2. DTOs with Full Documentation

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

export enum LegionaryRank {
  MILES = 'Miles',
  OPTIO = 'Optio',
  CENTURIO = 'Centurio',
  TRIBUNUS = 'Tribunus',
  LEGATUS = 'Legatus',
}

export class CreateLegionaryDto {
  @ApiProperty({ description: 'Name of the legionary', example: 'Marcus Aurelius', minLength: 2 })
  name: string;

  @ApiProperty({ description: 'Rank', enum: LegionaryRank, example: LegionaryRank.MILES })
  rank: LegionaryRank;

  @ApiProperty({ description: 'Assigned legion', example: 'Legio X Gemina' })
  legio: string;

  @ApiPropertyOptional({ description: 'Years of experience', example: 3, minimum: 0, maximum: 40 })
  experience?: number;
}

export class LegionaryResponseDto {
  @ApiProperty({ description: 'Legionary ID', example: '64a1b2c3d4e5f6a7b8c9d0e1' })
  id: string;

  @ApiProperty({ description: 'Name', example: 'Marcus Aurelius' })
  name: string;

  @ApiProperty({ description: 'Rank', enum: LegionaryRank })
  rank: LegionaryRank;

  @ApiProperty({ description: 'Legion', example: 'Legio X Gemina' })
  legio: string;

  @ApiProperty({ description: 'Experience', example: 5 })
  experience: number;

  @ApiProperty({ description: 'Recruitment date' })
  recruitedAt: Date;
}

3. Controller with Full Documentation

import { Controller, Get, Post, Put, Delete, Param, Body, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam, ApiQuery, ApiBearerAuth,
  ApiOkResponse, ApiCreatedResponse, ApiNotFoundResponse,
  ApiBadRequestResponse, ApiUnauthorizedResponse } from '@nestjs/swagger';

@ApiTags('Legiones')
@Controller('legiones')
export class LegionController {
  @ApiOperation({ summary: 'Get all legions' })
  @ApiOkResponse({ description: 'List of legions', type: [LegionaryResponseDto] })
  @ApiQuery({ name: 'rank', required: false, enum: LegionaryRank })
  @Get()
  findAll(@Query('rank') rank?: LegionaryRank) {}

  @ApiOperation({ summary: 'Get legionary by ID' })
  @ApiParam({ name: 'id', description: 'Legionary ID' })
  @ApiOkResponse({ type: LegionaryResponseDto })
  @ApiNotFoundResponse({ description: 'Legionary not found' })
  @Get(':id')
  findOne(@Param('id') id: string) {}

  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Recruit a legionary' })
  @ApiCreatedResponse({ type: LegionaryResponseDto })
  @ApiBadRequestResponse({ description: 'Invalid data' })
  @ApiUnauthorizedResponse({ description: 'Unauthorized' })
  @Post()
  create(@Body() dto: CreateLegionaryDto) {}
}

Module Summary

In this module, you learned:

  1. What OpenAPI/Swagger is - the API documentation standard
  2. Installation and configuration - DocumentBuilder and SwaggerModule
  3. Controller decorators - @ApiTags, @ApiOperation, @ApiResponse, @ApiParam, @ApiQuery
  4. DTO documentation - @ApiProperty with descriptions, examples, and validation
  5. Advanced responses - dedicated decorators for each status code
  6. Customization - personalizing Swagger UI
  7. CLI Plugin - automatic documentation generation
  8. Versioning - multiple docs for different API versions

Now your Chronicles of the Empire are complete! Every endpoint is documented like an imperial decree, and Swagger UI serves as the Forum of Annals for all developers.

Practical Exercise

Create the complete API documentation for Imperium Romanum:

Code for this lesson: src/app.controller.ts
// Main project: Complete Imperium API documentation
import { Controller, Get, Post, Put, Delete, Param, Body, Query } from '@nestjs/common';
import {
  ApiTags, ApiOperation, ApiParam, ApiQuery, ApiBearerAuth,
  ApiOkResponse, ApiCreatedResponse, ApiNotFoundResponse,
  ApiBadRequestResponse, ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

// ===== DTO =====

enum LegionaryRank {
  MILES = 'Miles',
  OPTIO = 'Optio',
  CENTURIO = 'Centurio',
  TRIBUNUS = 'Tribunus',
  LEGATUS = 'Legatus',
}

class CreateLegionaryDto {
  @ApiProperty({ description: 'Legionary name', example: 'Marcus Aurelius' })
  name: string;

  @ApiProperty({ description: 'Rank', enum: LegionaryRank, example: LegionaryRank.MILES })
  rank: LegionaryRank;

  @ApiProperty({ description: 'Assigned legion', example: 'Legio X Gemina' })
  legio: string;

  @ApiPropertyOptional({ description: 'Experience', example: 3, minimum: 0 })
  experience?: number;
}

class LegionaryResponseDto {
  @ApiProperty({ example: '64a1b2c3d4e5f6a7b8c9d0e1' })
  id: string;

  @ApiProperty({ example: 'Marcus Aurelius' })
  name: string;

  @ApiProperty({ enum: LegionaryRank })
  rank: LegionaryRank;

  @ApiProperty({ example: 'Legio X Gemina' })
  legio: string;

  @ApiProperty({ example: 5 })
  experience: number;
}

// ===== CONTROLLER =====

@ApiTags('Legiones')
@Controller('legiones')
class LegionController {
  @ApiOperation({ summary: 'Get all legions' })
  @ApiOkResponse({ description: 'List of legions', type: [LegionaryResponseDto] })
  @ApiQuery({ name: 'rank', required: false, enum: LegionaryRank })
  @Get()
  findAll(@Query('rank') rank?: LegionaryRank) {
    return [
      { id: '1', name: 'Marcus', rank: 'Centurio', legio: 'Legio X', experience: 10 },
    ];
  }

  @ApiOperation({ summary: 'Get a legionary by ID' })
  @ApiParam({ name: 'id', description: 'Legionary ID' })
  @ApiOkResponse({ type: LegionaryResponseDto })
  @ApiNotFoundResponse({ description: 'Legionary not found' })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return { id, name: 'Marcus', rank: 'Centurio', legio: 'Legio X', experience: 10 };
  }

  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Recruit a legionary' })
  @ApiCreatedResponse({ type: LegionaryResponseDto })
  @ApiBadRequestResponse({ description: 'Invalid data' })
  @ApiUnauthorizedResponse({ description: 'Unauthorized' })
  @Post()
  create(@Body() dto: CreateLegionaryDto) {
    return { id: '2', ...dto, experience: dto.experience || 0 };
  }
}

console.log("Complete Imperium API documentation");
console.log("DTO: CreateLegionaryDto, LegionaryResponseDto");
console.log("Controller: LegionController with full documentation");
console.log("Decorators: Tags, Operation, Param, Query, Response, Auth");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which Swagger decorators should a well-documented GET /:id endpoint have?

  2. 2. What is the best way to secure access to Swagger UI in a production environment?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Order the elements of complete API documentation from configuration to presentation:

  • Code editor

    Create CreateArmyDto with enum ArmyUnit, nested CommanderDto, a provinces array, and soldiers validation

  • Click in order

    Arrange the elements of a documented DTO field from decorator to type:

  • Horizontal ordering

    Arrange the SwaggerModule.setup() arguments in the correct order:

  • Vertical ordering

    Order the versioning strategies from the simplest to the most advanced:

  • Click in order

    Arrange the elements of the Swagger decorators import in the correct order:

  • Vertical ordering

    Order the stages of creating Swagger documentation from installation to usage:

  • Horizontal ordering

    Arrange the elements of the @ApiResponse decorator in the correct order:

  1. QuestionFull Documentation for a GET Endpoint
  2. Put in orderElements of Complete API Documentation
  3. Coding taskAdvanced DTO with Validation
  4. Click in orderStructure of a Documented DTO
  5. Put in orderSwaggerModule.setup with Options
  6. QuestionSecuring Swagger in Production
  7. Put in orderAPI Versioning Strategies
  8. QuestionSummary: The @ApiTags Decorator
  9. Click in orderComplete Swagger Decorators Import
  10. Put in orderThe Process of Creating Swagger Documentation
  11. Put in orderFull @ApiResponse Decorator
  12. QuestionSummary: Generating the OpenAPI Document
  13. Project to submitSubmit the Chronicles of the Empire Project
  14. VideoModule Summary

Useful articles