or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

decorators.mddocument-builder.mdindex.mdinterfaces.mdswagger-module.mdtype-helpers.md
tile.json

tessl/npm-nestjs--swagger

OpenAPI (Swagger) module for Nest framework enabling automatic API documentation generation from TypeScript decorators

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@nestjs/swagger@11.2.x

To install, run

npx @tessl/cli install tessl/npm-nestjs--swagger@11.2.0

index.mddocs/

@nestjs/swagger

@nestjs/swagger is the official OpenAPI (Swagger) integration library for NestJS applications. It provides comprehensive decorators, utilities, and configuration tools to automatically generate OpenAPI 3.0 specifications from your NestJS code, complete with interactive Swagger UI documentation.

Package Information

FieldValue
Package@nestjs/swagger
Version11.2.0
LicenseMIT
Dependencies@nestjs/common, @nestjs/core, reflect-metadata
PlatformNode.js
TypeScriptFull TypeScript support with comprehensive type definitions

Installation

npm install @nestjs/swagger

Core Imports

ES Modules (ESM)

import { 
  DocumentBuilder, 
  SwaggerModule, 
  ApiProperty, 
  ApiOperation,
  ApiResponse 
} from '@nestjs/swagger';

CommonJS

const { 
  DocumentBuilder, 
  SwaggerModule, 
  ApiProperty, 
  ApiOperation,
  ApiResponse 
} = require('@nestjs/swagger');

Basic Usage

Quick Setup

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

  // Create OpenAPI document configuration
  const config = new DocumentBuilder()
    .setTitle('My API')
    .setDescription('API description')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  // Generate OpenAPI document
  const document = SwaggerModule.createDocument(app, config);
  
  // Setup Swagger UI
  SwaggerModule.setup('api', app, document);

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

Annotating DTOs and Controllers

import { ApiProperty, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { Controller, Post, Body } from '@nestjs/common';

class CreateUserDto {
  @ApiProperty({ description: 'User name', example: 'John Doe' })
  name: string;

  @ApiProperty({ description: 'User email', example: 'john@example.com' })
  email: string;
}

@Controller('users')
export class UsersController {
  @Post()
  @ApiOperation({ summary: 'Create a new user' })
  @ApiResponse({ status: 201, description: 'User successfully created' })
  @ApiResponse({ status: 400, description: 'Bad request' })
  async create(@Body() createUserDto: CreateUserDto) {
    // Implementation
  }
}

Architecture

Core Components

@nestjs/swagger is built around six major modules that work together to provide comprehensive OpenAPI integration:

  1. Decorators - Annotation system for marking up classes, methods, and properties with OpenAPI metadata
  2. DocumentBuilder - Configuration builder for creating OpenAPI document specifications
  3. SwaggerModule - Integration layer that connects NestJS applications with Swagger UI
  4. Type Helpers - Utility functions for creating derived types (Partial, Pick, Omit, Intersection)
  5. Interfaces - Complete TypeScript definitions for OpenAPI 3.0 specification objects
  6. Utils - Helper functions for schema references and path generation

Metadata Flow

NestJS Application
       ↓
   Decorators (Add OpenAPI metadata to classes/methods)
       ↓
   DocumentBuilder (Configure document structure)
       ↓
   SwaggerModule (Generate OpenAPI spec + Setup UI)
       ↓
   Swagger UI (Interactive documentation)

Key Concepts

  • Decorators: TypeScript decorators that attach OpenAPI metadata to classes, methods, and properties
  • Schema Generation: Automatic conversion of TypeScript types to JSON Schema definitions
  • Document Configuration: Builder pattern for creating comprehensive OpenAPI documents
  • UI Integration: Seamless setup of interactive Swagger UI with customization options
  • Type Safety: Full TypeScript support with compile-time validation

Capabilities

API Annotation System

Comprehensive decorator system for annotating every aspect of your API:

import { 
  ApiProperty, 
  ApiOperation, 
  ApiResponse, 
  ApiParam, 
  ApiQuery,
  ApiHeader,
  ApiBody
} from '@nestjs/swagger';

→ Complete decorators reference

Document Configuration

Powerful builder for creating OpenAPI document specifications:

import { DocumentBuilder } from '@nestjs/swagger';

const config = new DocumentBuilder()
  .setTitle('API')
  .setDescription('API description')
  .setVersion('1.0')
  .addServer('https://api.example.com')
  .addBearerAuth()
  .addTag('users', 'User management operations')
  .build();

→ DocumentBuilder API reference

NestJS Integration

Seamless integration with NestJS applications:

import { SwaggerModule } from '@nestjs/swagger';

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

// Setup Swagger UI with customization
SwaggerModule.setup('api', app, document, {
  swaggerOptions: {
    persistAuthorization: true,
  },
});

→ SwaggerModule API reference

Type Utilities

Advanced type manipulation functions for creating derived DTOs:

import { 
  PartialType, 
  PickType, 
  OmitType, 
  IntersectionType 
} from '@nestjs/swagger';

// Create partial type
class UpdateUserDto extends PartialType(CreateUserDto) {}

// Pick specific properties  
class UserSummaryDto extends PickType(User, ['id', 'name'] as const) {}

// Combine multiple types
class ExtendedUserDto extends IntersectionType(CreateUserDto, BaseDto) {}

→ Type helpers reference

Schema References and Utilities

Utilities for creating schema references and manipulating OpenAPI schemas:

import { getSchemaPath, refs } from '@nestjs/swagger';

// Get schema reference path for a model class or string
function getSchemaPath(model: string | Function): string;

// Create multiple schema references from model classes
function refs(...models: Function[]): ReferenceObject[];

// Usage examples
const userSchemaRef = getSchemaPath(User);           // "#/components/schemas/User"
const productSchemaRef = getSchemaPath('Product');   // "#/components/schemas/Product"

// Create multiple schema references
const schemaRefs = refs(User, Product, Order);
// Returns: [
//   { $ref: "#/components/schemas/User" },
//   { $ref: "#/components/schemas/Product" }, 
//   { $ref: "#/components/schemas/Order" }
// ]

Note: These utilities are especially useful when creating complex response schemas or defining relationships between models in your OpenAPI documentation.

OpenAPI Interfaces

Complete TypeScript definitions for OpenAPI 3.0 specification:

import { 
  OpenAPIObject, 
  SchemaObject, 
  OperationObject,
  ResponseObject,
  ParameterObject 
} from '@nestjs/swagger';

→ Interfaces reference

Security Integration

Built-in support for all OpenAPI security schemes:

import { 
  ApiSecurity, 
  ApiBearerAuth, 
  ApiBasicAuth, 
  ApiOAuth2,
  ApiCookieAuth 
} from '@nestjs/swagger';

@ApiBearerAuth() // JWT Bearer token
@ApiBasicAuth()  // HTTP Basic auth
@ApiOAuth2(['read', 'write']) // OAuth2 with scopes
class SecureController {}

Advanced Features

  • Plugin System: Automatic metadata generation via TypeScript compiler plugin
  • Custom Extensions: Support for OpenAPI extensions (x-* properties)
  • Validation Integration: Works seamlessly with class-validator decorators
  • Multi-format Support: JSON and YAML document generation
  • UI Customization: Extensive Swagger UI theming and behavior options

This package provides everything needed to create professional, interactive API documentation for NestJS applications with minimal effort while maintaining full type safety and extensive customization options.