Docs are a work in progress - contributions welcome
Logonestjs-openapi
API Reference

generate()

Generate OpenAPI specification from a NestJS application

Generates an OpenAPI specification from a NestJS application by analyzing TypeScript source code.

Signature

function generate(configPath: string): Promise<GenerateResult>;

Parameters

ParameterTypeDescription
configPathstringPath to the configuration file (relative or absolute)

Returns

Promise<GenerateResult> - Resolves when generation is complete.

GenerateResult

interface GenerateResult {
  /** Absolute path where the OpenAPI spec was written */
  readonly outputPath: string;

  /** Number of paths in the generated spec */
  readonly pathCount: number;

  /** Number of operations in the generated spec */
  readonly operationCount: number;

  /** Number of schemas in the generated spec */
  readonly schemaCount: number;

  /** Validation result for broken $ref checks */
  readonly validation: ValidationResult;
}

Example

Basic Usage

import { generate } from 'nestjs-openapi';

const result = await generate('./openapi.config.ts');

console.log(`Output: ${result.outputPath}`);
console.log(`Paths: ${result.pathCount}`);
console.log(`Operations: ${result.operationCount}`);
console.log(`Schemas: ${result.schemaCount}`);

With Error Handling

import { generate } from 'nestjs-openapi';

try {
  const result = await generate('./openapi.config.ts');
  console.log(`Generated ${result.operationCount} operations`);
} catch (error) {
  if (error instanceof Error) {
    console.error(`Generation failed: ${error.message}`);
  }
  process.exit(1);
}

In a Build Script

// scripts/generate-openapi.ts
import { generate } from 'nestjs-openapi';

async function main() {
  const configs = [
    'apps/api/openapi.config.ts',
    'apps/admin/openapi.config.ts',
  ];

  for (const config of configs) {
    console.log(`Generating from ${config}...`);
    const result = await generate(config);
    console.log(
      `  -> ${result.outputPath} (${result.operationCount} operations)`,
    );
  }
}

main().catch(console.error);

With Timing

import { generate } from 'nestjs-openapi';

const start = performance.now();
const result = await generate('./openapi.config.ts');
const duration = ((performance.now() - start) / 1000).toFixed(2);

console.log(`Generated in ${duration}s`);
console.log(`  ${result.pathCount} paths`);
console.log(`  ${result.operationCount} operations`);
console.log(`  ${result.schemaCount} schemas`);

Spec Validation

generate() always returns a validation summary for broken $refs. The CLI prints warnings when refs are missing but still writes the spec.

import { generate, formatValidationResult } from 'nestjs-openapi';

const result = await generate('./openapi.config.ts');

if (!result.validation.valid) {
  console.warn(formatValidationResult(result.validation));
}

See Spec Validation for the full API.

Errors

The function may throw the following errors:

ErrorCause
ErrorConfig file not found
ErrorInvalid configuration (missing required fields)
Errortsconfig.json not found
ErrorEntry module file not found
ErrorAppModule class not found in entry file
try {
  await generate('./openapi.config.ts');
} catch (error) {
  if (error instanceof Error) {
    if (error.message.includes('Configuration file not found')) {
      // Handle missing config
    } else if (error.message.includes('tsconfig.json not found')) {
      // Handle missing tsconfig
    } else if (error.message.includes('Entry class')) {
      // Handle missing AppModule
    }
  }
}

Behavior

  1. Loads configuration from the specified path
  2. Resolves tsconfig.json (uses files.tsconfig when provided; otherwise searches upward from the entry file)
  3. Parses TypeScript source files using ts-morph
  4. Traverses modules following @Module({ imports })
  5. Extracts controllers and their HTTP methods
  6. Generates schemas from DTO files (based on dtoGlob) and resolves missing types when refs are detected
  7. Extracts validation constraints from class-validator decorators
  8. Transforms to OpenAPI 3.0.3 specification
  9. Validates the spec for broken $refs
  10. Writes output to the specified file (JSON or YAML)

Path Resolution

Paths in the config file are resolved relative to the config file location:

// openapi.config.ts in /app/configs/
export default defineConfig({
  output: '../openapi.json', // -> /app/openapi.json
  files: {
    entry: '../src/app.module.ts', // -> /app/src/app.module.ts
    tsconfig: '../tsconfig.json', // -> /app/tsconfig.json
    dtoGlob: '../src/**/*.dto.ts', // -> /app/src/**/*.dto.ts
  },
});

CLI Reference

The generate() function is what the CLI uses internally.

Usage

npx nestjs-openapi generate -c <config-path> [options]

Options

OptionDescription
-c, --configPath to configuration file (required)
-f, --formatOutput format: json or yaml (overrides config)
-q, --quietSuppress output (only show errors)
-d, --debugEnable debug output (verbose logging, stack traces)
-h, --helpShow help message
-v, --versionShow version

Examples

# Basic generation
npx nestjs-openapi generate -c openapi.config.ts

# Override output format
npx nestjs-openapi generate -c openapi.config.ts --format yaml

# Quiet mode for CI
npx nestjs-openapi generate -c openapi.config.ts --quiet

# Debug mode for troubleshooting
npx nestjs-openapi generate -c openapi.config.ts --debug

Debug Mode

The --debug flag enables verbose logging that shows:

  • Config loading and validation
  • Module traversal progress
  • Schema generation details
  • Full stack traces on errors

This is useful for troubleshooting issues with type resolution or understanding why certain schemas aren't being generated.

Programmatic Equivalent

import { generate } from 'nestjs-openapi';
await generate('./openapi.config.ts');

See Also

On this page