CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nestjs--swagger

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

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

document-builder.mddocs/

DocumentBuilder

The DocumentBuilder class provides a fluent, builder-pattern interface for creating and configuring OpenAPI document specifications. It serves as the foundation for generating comprehensive API documentation by allowing you to set metadata, servers, security schemes, and other OpenAPI document properties.

Class Overview

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

class DocumentBuilder {
  constructor();
  build(): Omit<OpenAPIObject, 'paths'>;
}

The DocumentBuilder uses the builder pattern, where each method returns this to allow method chaining, and finally build() returns the configured OpenAPI document specification.

Basic Information Methods

setTitle { .api }

setTitle(title: string): this

Sets the title of the API in the OpenAPI document.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .build();

// Results in:
// {
//   "info": {
//     "title": "E-Commerce API"
//   }
// }

setDescription { .api }

setDescription(description: string): this

Sets the description of the API, supporting Markdown formatting.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setDescription(`
    A comprehensive API for managing e-commerce operations.
    
    ## Features
    - Product management
    - Order processing  
    - User authentication
    - Payment processing
  `)
  .build();

setVersion { .api }

setVersion(version: string): this

Sets the version of the API following semantic versioning.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setVersion('2.1.0')
  .build();

setTermsOfService { .api }

setTermsOfService(termsOfService: string): this

Sets the URL to the Terms of Service for the API.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setTermsOfService('https://example.com/terms')
  .build();

setContact { .api }

setContact(name: string, url: string, email: string): this

Sets contact information for the API including name, URL, and email.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setContact('API Team', 'https://example.com/contact', 'api@example.com')
  .build();

// Results in:
// {
//   "info": {
//     "contact": {
//       "name": "API Team",
//       "url": "https://example.com/contact", 
//       "email": "api@example.com"
//     }
//   }
// }

setLicense { .api }

setLicense(name: string, url: string): this

Sets license information for the API.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setLicense('MIT', 'https://opensource.org/licenses/MIT')
  .build();

// Results in:
// {
//   "info": {
//     "license": {
//       "name": "MIT",
//       "url": "https://opensource.org/licenses/MIT"
//     }
//   }
// }

setOpenAPIVersion { .api }

setOpenAPIVersion(version: string): this

Sets the OpenAPI specification version. Must follow the format "x.x.x" (e.g., "3.0.0").

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setOpenAPIVersion('3.0.3') // Defaults to 3.0.0 if not specified
  .build();

Server Configuration

addServer { .api }

addServer(
  url: string, 
  description?: string, 
  variables?: Record<string, ServerVariableObject>
): this

Adds a server to the OpenAPI document. Multiple servers can be added to represent different environments.

Type Definitions:

interface ServerVariableObject {
  default: string;
  description?: string;
  enum?: string[];
}

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addServer('https://api.example.com', 'Production server')
  .addServer('https://staging-api.example.com', 'Staging server')
  .addServer('http://localhost:3000', 'Development server')
  .build();

// Server with variables
const configWithVars = new DocumentBuilder()
  .setTitle('Multi-tenant API')
  .addServer(
    'https://{tenant}.api.example.com/{version}',
    'Tenant-specific API server',
    {
      tenant: {
        default: 'demo',
        description: 'Tenant identifier',
        enum: ['demo', 'staging', 'production']
      },
      version: {
        default: 'v1',
        description: 'API version',
        enum: ['v1', 'v2']
      }
    }
  )
  .build();

Documentation and Tagging

setExternalDoc { .api }

setExternalDoc(description: string, url: string): this

Sets external documentation reference for the entire API.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setExternalDoc('API Documentation', 'https://docs.example.com/api')
  .build();

// Results in:
// {
//   "externalDocs": {
//     "description": "API Documentation",
//     "url": "https://docs.example.com/api"
//   }
// }

addTag { .api }

addTag(
  name: string, 
  description?: string, 
  externalDocs?: ExternalDocumentationObject
): this

Adds tags for grouping operations in the Swagger UI.

Type Definitions:

interface ExternalDocumentationObject {
  description?: string;
  url: string;
}

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addTag('Products', 'Product management operations')
  .addTag('Orders', 'Order processing and tracking')
  .addTag('Users', 'User authentication and profiles', {
    description: 'User guide',
    url: 'https://docs.example.com/users'
  })
  .addTag('Payments', 'Payment processing and billing')
  .build();

// Results in tags that group related endpoints in Swagger UI

Extensions and Custom Properties

addExtension { .api }

addExtension(
  extensionKey: string, 
  extensionProperties: any, 
  location?: ExtensionLocation
): this

Adds custom OpenAPI extensions (x-* properties) to the document.

Type Definitions:

type ExtensionLocation = 'root' | 'info' | 'components';

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addExtension('x-api-id', 'ecommerce-api-v2')
  .addExtension('x-logo', {
    url: 'https://example.com/logo.png',
    altText: 'Company Logo'
  })
  .addExtension('x-code-samples', {
    languages: ['javascript', 'python', 'curl']
  }, 'info') // Add to info object instead of root
  .build();

// Extensions must start with 'x-' prefix or an error will be thrown

Security Configuration

addSecurity { .api }

addSecurity(name: string, options: SecuritySchemeObject): this

Adds a security scheme definition to the OpenAPI document components.

Type Definitions:

interface SecuritySchemeObject {
  type: 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';
  description?: string;
  name?: string; // For apiKey
  in?: 'query' | 'header' | 'cookie'; // For apiKey
  scheme?: string; // For http (e.g., 'basic', 'bearer')
  bearerFormat?: string; // For http bearer
  flows?: OAuthFlowsObject; // For oauth2
  openIdConnectUrl?: string; // For openIdConnect
}

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addSecurity('custom-api-key', {
    type: 'apiKey',
    in: 'header',
    name: 'X-API-Key',
    description: 'Custom API key authentication'
  })
  .addSecurity('jwt-auth', {
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
    description: 'JWT token authentication'
  })
  .build();

addBearerAuth { .api }

addBearerAuth(
  options?: SecuritySchemeObject, 
  name?: string
): this

Adds JWT Bearer token authentication. Defaults to name 'bearer'.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBearerAuth() // Default configuration
  .build();

// Custom Bearer auth
const customConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBearerAuth({
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
    description: 'JWT authorization token'
  }, 'jwt-token')
  .build();

addOAuth2 { .api }

addOAuth2(
  options?: SecuritySchemeObject, 
  name?: string
): this

Adds OAuth2 authentication configuration. Defaults to name 'oauth2'.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addOAuth2({
    type: 'oauth2',
    flows: {
      authorizationCode: {
        authorizationUrl: 'https://auth.example.com/oauth/authorize',
        tokenUrl: 'https://auth.example.com/oauth/token',
        scopes: {
          'read': 'Read access',
          'write': 'Write access',
          'admin': 'Administrative access'
        }
      },
      clientCredentials: {
        tokenUrl: 'https://auth.example.com/oauth/token',
        scopes: {
          'service': 'Service-to-service access'
        }
      }
    }
  })
  .build();

addApiKey { .api }

addApiKey(
  options?: SecuritySchemeObject, 
  name?: string
): this

Adds API key authentication. Defaults to header-based API key with name 'api_key'.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addApiKey() // Default: header-based with name 'api_key'
  .build();

// Custom API key configuration
const customConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addApiKey({
    type: 'apiKey',
    in: 'query',
    name: 'access_token',
    description: 'API access token'
  }, 'query-token')
  .build();

addBasicAuth { .api }

addBasicAuth(
  options?: SecuritySchemeObject, 
  name?: string
): this

Adds HTTP Basic authentication. Defaults to name 'basic'.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBasicAuth() // Default Basic auth
  .build();

// Custom Basic auth
const customConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBasicAuth({
    type: 'http',
    scheme: 'basic',
    description: 'Username and password authentication'
  }, 'http-basic')
  .build();

addCookieAuth { .api }

addCookieAuth(
  cookieName?: string, 
  options?: SecuritySchemeObject, 
  securityName?: string
): this

Adds cookie-based authentication. Defaults to cookie name 'connect.sid' and security name 'cookie'.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addCookieAuth() // Default: 'connect.sid' cookie
  .build();

// Custom cookie auth
const customConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addCookieAuth('sessionId', {
    type: 'apiKey',
    in: 'cookie',
    description: 'Session cookie authentication'
  }, 'session-auth')
  .build();

addSecurityRequirements { .api }

addSecurityRequirements(
  name: string | SecurityRequirementObject, 
  requirements?: string[]
): this

Adds global security requirements that apply to all operations unless overridden.

Type Definitions:

type SecurityRequirementObject = Record<string, string[]>;

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBearerAuth()
  .addApiKey()
  .addSecurityRequirements('bearer') // All endpoints require Bearer token
  .addSecurityRequirements('api_key') // Alternative: API key
  .build();

// OAuth2 with specific scopes
const oauthConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addOAuth2()
  .addSecurityRequirements('oauth2', ['read', 'write']) // Require specific scopes
  .build();

// Multiple requirements (both must be satisfied)
const multiConfig = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addBearerAuth()
  .addApiKey()
  .addSecurityRequirements({ 'bearer': [], 'api_key': [] })
  .build();

Global Configuration

addGlobalResponse { .api }

addGlobalResponse(...responses: ApiResponseOptions[]): this

Adds global response definitions that apply to all operations.

Type Definitions:

interface ApiResponseOptions {
  status?: number | 'default';
  description?: string;
  type?: any;
  isArray?: boolean;
  schema?: SchemaObject & Partial<ReferenceObject>;
}

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addGlobalResponse({
    status: 401,
    description: 'Unauthorized - Invalid or missing authentication'
  })
  .addGlobalResponse({
    status: 403,
    description: 'Forbidden - Insufficient permissions'
  })
  .addGlobalResponse({
    status: 500,
    description: 'Internal server error',
    schema: {
      type: 'object',
      properties: {
        error: { type: 'string' },
        message: { type: 'string' },
        timestamp: { type: 'string', format: 'date-time' }
      }
    }
  })
  .build();

addGlobalParameters { .api }

addGlobalParameters(
  ...parameters: Omit<ParameterObject, 'example' | 'examples'>[]
): this

Adds global parameters that apply to all operations.

Type Definitions:

interface ParameterObject {
  name: string;
  in: 'query' | 'header' | 'path' | 'cookie';
  description?: string;
  required?: boolean;
  deprecated?: boolean;
  allowEmptyValue?: boolean;
  schema?: SchemaObject;
  style?: ParameterStyle;
  explode?: boolean;
  allowReserved?: boolean;
}

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .addGlobalParameters(
    {
      name: 'X-Request-ID',
      in: 'header',
      description: 'Unique request identifier for tracing',
      required: false,
      schema: {
        type: 'string',
        format: 'uuid'
      }
    },
    {
      name: 'Accept-Language',
      in: 'header',
      description: 'Preferred language for response',
      required: false,
      schema: {
        type: 'string',
        enum: ['en-US', 'es-ES', 'fr-FR'],
        default: 'en-US'
      }
    }
  )
  .build();

Building the Document

build { .api }

build(): Omit<OpenAPIObject, 'paths'>

Finalizes and returns the configured OpenAPI document specification. The paths property is omitted as it will be generated from your NestJS controllers and decorators.

Usage:

const config = new DocumentBuilder()
  .setTitle('E-Commerce API')
  .setDescription('Comprehensive e-commerce platform API')
  .setVersion('2.0.0')
  .addServer('https://api.example.com', 'Production')
  .addServer('http://localhost:3000', 'Development')
  .addBearerAuth()
  .addTag('Products', 'Product catalog operations')
  .addTag('Orders', 'Order management')
  .build();

// Use with SwaggerModule
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

Complete Example

Comprehensive API Configuration

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

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

  const config = new DocumentBuilder()
    // Basic information
    .setTitle('E-Commerce Platform API')
    .setDescription(`
      A comprehensive RESTful API for e-commerce operations.
      
      ## Authentication
      This API uses JWT Bearer tokens for authentication. Include your token in the Authorization header.
      
      ## Rate Limiting
      API calls are limited to 1000 requests per hour per API key.
      
      ## Support
      For API support, contact our developer team.
    `)
    .setVersion('2.1.0')
    .setTermsOfService('https://example.com/terms')
    .setContact('API Team', 'https://example.com/contact', 'api-support@example.com')
    .setLicense('MIT', 'https://opensource.org/licenses/MIT')
    
    // Servers
    .addServer('https://api.example.com', 'Production server')
    .addServer('https://staging-api.example.com', 'Staging server')  
    .addServer('http://localhost:3000', 'Development server')
    
    // External documentation
    .setExternalDoc('Complete API Guide', 'https://docs.example.com')
    
    // Tags for organization
    .addTag('Authentication', 'User authentication and authorization')
    .addTag('Products', 'Product catalog and inventory management')
    .addTag('Orders', 'Order processing and fulfillment')
    .addTag('Users', 'User profile and account management')
    .addTag('Payments', 'Payment processing and billing')
    .addTag('Admin', 'Administrative operations', {
      description: 'Admin operations guide',
      url: 'https://docs.example.com/admin'
    })
    
    // Security schemes
    .addBearerAuth({
      type: 'http',
      scheme: 'bearer', 
      bearerFormat: 'JWT',
      description: 'JWT authorization token'
    }, 'jwt-auth')
    .addApiKey({
      type: 'apiKey',
      in: 'header',
      name: 'X-API-Key',
      description: 'API key for service-to-service communication'
    }, 'api-key')
    .addOAuth2({
      type: 'oauth2',
      flows: {
        authorizationCode: {
          authorizationUrl: 'https://auth.example.com/oauth/authorize',
          tokenUrl: 'https://auth.example.com/oauth/token',
          scopes: {
            'products:read': 'Read product information',
            'products:write': 'Create and modify products',
            'orders:read': 'Read order information',
            'orders:write': 'Create and modify orders',
            'admin': 'Full administrative access'
          }
        }
      }
    })
    
    // Global security requirements (JWT required by default)
    .addSecurityRequirements('jwt-auth')
    
    // Global responses
    .addGlobalResponse({
      status: 401,
      description: 'Unauthorized - Authentication required'
    })
    .addGlobalResponse({
      status: 403,
      description: 'Forbidden - Insufficient permissions'
    })
    .addGlobalResponse({
      status: 429,
      description: 'Too Many Requests - Rate limit exceeded'
    })
    .addGlobalResponse({
      status: 500,
      description: 'Internal Server Error'
    })
    
    // Global parameters
    .addGlobalParameters(
      {
        name: 'X-Request-ID',
        in: 'header',
        description: 'Unique identifier for request tracing',
        required: false,
        schema: { type: 'string', format: 'uuid' }
      },
      {
        name: 'Accept-Language',
        in: 'header', 
        description: 'Preferred response language',
        required: false,
        schema: { 
          type: 'string',
          enum: ['en-US', 'es-ES', 'fr-FR'],
          default: 'en-US'
        }
      }
    )
    
    // Custom extensions
    .addExtension('x-api-id', 'ecommerce-platform')
    .addExtension('x-logo', {
      url: 'https://example.com/logo.png',
      altText: 'E-Commerce Platform'
    })
    
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api-docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true,
      displayRequestDuration: true
    }
  });

  await app.listen(3000);
}

bootstrap();

This comprehensive DocumentBuilder configuration provides a professional, well-documented API specification that includes all necessary metadata, security schemes, and organizational structure for a production e-commerce platform.

docs

decorators.md

document-builder.md

index.md

interfaces.md

swagger-module.md

type-helpers.md

tile.json