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
| Parameter | Type | Description |
|---|---|---|
configPath | string | Path 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:
| Error | Cause |
|---|---|
Error | Config file not found |
Error | Invalid configuration (missing required fields) |
Error | tsconfig.json not found |
Error | Entry module file not found |
Error | AppModule 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
- Loads configuration from the specified path
- Resolves tsconfig.json (uses
files.tsconfigwhen provided; otherwise searches upward from the entry file) - Parses TypeScript source files using ts-morph
- Traverses modules following
@Module({ imports }) - Extracts controllers and their HTTP methods
- Generates schemas from DTO files (based on
dtoGlob) and resolves missing types when refs are detected - Extracts validation constraints from class-validator decorators
- Transforms to OpenAPI 3.0.3 specification
- Validates the spec for broken
$refs - 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
| Option | Description |
|---|---|
-c, --config | Path to configuration file (required) |
-f, --format | Output format: json or yaml (overrides config) |
-q, --quiet | Suppress output (only show errors) |
-d, --debug | Enable debug output (verbose logging, stack traces) |
-h, --help | Show help message |
-v, --version | Show 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 --debugDebug 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
- defineConfig() - Configuration helper
- Configuration Guide - Full config reference
- Programmatic API - Advanced usage patterns