npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@eqxjs/swagger-codegen

v1.0.1

Published

CLI tool to generate NestJS modules, controllers, services, and DTOs from Swagger/OpenAPI files

Downloads

31

Readme

Swagger NestJS Codegen

A TypeScript CLI tool to generate NestJS modules, controllers, services, and DTOs from Swagger/OpenAPI files.

📚 Quick Start Guide | 📖 Format Comparison | 🔄 OpenAPI vs Swagger

Features

  • ✅ Parse Swagger/OpenAPI 2.0 and 3.0 files (JSON or YAML)
  • ✅ Generate DTOs from request/response schemas with @ApiProperty decorators
  • Validation decorators enabled by default - class-validator integration (--no-validate to skip)
  • Test files generated by default - Comprehensive test suites (--no-test to skip)
  • ✅ Generate Services with typed method signatures and JSDoc comments
  • ✅ Generate Controllers with proper HTTP method decorators and route paths
  • ✅ Generate Modules with proper dependency injection setup
  • Generate Swagger setup helper - index.ts with DocumentBuilder configuration
  • ✅ Generate Client Services (TypeScript + Axios) for calling APIs
  • DTOs-only mode - Generate just data models with --mode dtos
  • ✅ Support for path parameters, query parameters, and request bodies
  • ✅ Support for array responses and nested schemas
  • ✅ Automatic type inference from Swagger schemas
  • ✅ Multiple generation modes: server, client, both, or dtos
  • Auto dependency detection - Shows required npm install commands

📖 See FORMATS.md for detailed JSON vs YAML format comparison 📖 See OPENAPI-COMPARISON.md for Swagger 2.0 vs OpenAPI 3.0 differences

Example Files Included

| File | Format | Version | Description | |------|--------|---------|-------------| | example-swagger.json | JSON | Swagger 2.0 | Users & Posts API | | example-swagger.yaml | YAML | Swagger 2.0 | Users & Posts API | | openapi3-example.json | JSON | OpenAPI 3.0 | Products & Categories API | | openapi3-example.yaml | YAML | OpenAPI 3.0 | Products & Categories API |

Installation

From NPM

npm install -g @eqxjs/swagger-codegen

From Source

git clone <repository-url>
cd swagger-nestjs-codegen
npm install
npm run build

Usage

Generation Modes

The generator supports three modes:

  • server (default): Generate NestJS server-side code (controllers, services, modules)
  • client: Generate TypeScript client services using Axios
  • both: Generate both server and client code

Development Mode

# Server mode (default) - Generate NestJS controllers, services, and modules
npm run dev -- generate -i ./example-swagger.json -o ./generated

# Client mode - Generate TypeScript client services with Axios
npm run dev -- generate -i ./example-swagger.json -o ./generated --mode client

# Both modes - Generate both server and client code
npm run dev -- generate -i ./example-swagger.json -o ./generated --mode both

# Swagger 2.0 - JSON format
npm run dev -- generate -i ./example-swagger.json -o ./generated

# Swagger 2.0 - YAML format
npm run dev -- generate -i ./example-swagger.yaml -o ./generated

# OpenAPI 3.0 - JSON format
npm run dev -- generate -i ./openapi3-example.json -o ./generated

# OpenAPI 3.0 - YAML format
npm run dev -- generate -i ./openapi3-example.yaml -o ./generated

Production Mode

# Using the global CLI
eqxjs-swagger-codegen generate -i ./swagger.json -o ./generated

# Using npx (no installation required)
npx @eqxjs/swagger-codegen generate -i ./swagger.json -o ./generated

# With YAML files
eqxjs-swagger-codegen generate -i ./swagger.yaml -o ./generated

# Local installation
node dist/cli.js generate -i ./swagger.json -o ./generated

Command Options

eqxjs-swagger-codegen generate [options]

Options:
  -i, --input <path>    Path to Swagger/OpenAPI file (JSON or YAML) [required]
  -o, --output <path>   Output directory for generated files (default: "./generated")
  -m, --mode <mode>     Generation mode: server, client, both, or dtos (default: "server")
  --no-test            Skip generating test files (.spec.ts) [tests generated by default]
  --no-validate        Skip adding class-validator decorators [validation enabled by default]
  -h, --help           Display help for command

Default Behavior (NEW):

  • Test files are generated by default - Use --no-test to skip
  • Validation decorators are added by default - Use --no-validate to skip
  • 🚀 DTOs-only mode is now --mode dtos instead of --only-dtos flag

Test File Generation (Enabled by Default)

Test files are now generated by default for all controllers, services, and DTOs. Use --no-test to skip:

# Generate with test files (DEFAULT BEHAVIOR)
eqxjs-swagger-codegen generate -i ./example-swagger.json -o ./generated

# Skip test generation
eqxjs-swagger-codegen generate -i ./swagger.json -o ./generated --no-test

# Development mode without tests
npm run dev -- generate -i ./example-swagger.json -o ./generated --no-test

Validation Decorators (Enabled by Default)

Validation decorators are now added by default to all DTO properties. Use --no-validate to skip:

# Generate DTOs with validation decorators (DEFAULT BEHAVIOR)
eqxjs-swagger-codegen generate -i ./swagger.json -o ./generated

# Skip validation decorators
eqxjs-swagger-codegen generate -i ./swagger.json -o ./generated --no-validate

# Skip both tests and validation
eqxjs-swagger-codegen generate -i ./swagger.json -o ./generated --no-test --no-validate

Generated validators include:

  • @IsString(), @IsNumber(), @IsInt(), @IsBoolean(), @IsDate() for basic types
  • @IsEmail() for email format
  • @IsUUID() for UUID format
  • @IsUrl() for URL format
  • @IsEnum() for enum values
  • @IsArray() with @IsString({ each: true }) for arrays
  • @ValidateNested() with @Type() for nested objects
  • @Min(), @Max() for number constraints
  • @MinLength(), @MaxLength() for string length
  • @Matches() for regex patterns

Example output:

import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsEmail, IsInt, Min } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @IsEmail()
  @ApiProperty({ description: 'User email', type: String })
  email!: string;

  @IsInt()
  @Min(18)
  @ApiProperty({ description: 'User age', type: Number })
  age!: number;
}

DTOs-Only Mode

Use --mode dtos to generate only Data Transfer Objects without services, controllers, or modules:

# Generate only DTOs (with validation and tests by default)
eqxjs-swagger-codegen generate -i ./swagger.json -o ./dtos --mode dtos

# DTOs without validators
eqxjs-swagger-codegen generate -i ./swagger.json -o ./dtos --mode dtos --no-validate

# DTOs without tests
eqxjs-swagger-codegen generate -i ./swagger.json -o ./dtos --mode dtos --no-test

# Plain DTOs (no validation, no tests)
eqxjs-swagger-codegen generate -i ./swagger.json -o ./dtos --mode dtos --no-validate --no-test

# Using npx
npx @eqxjs/swagger-codegen generate -i ./api.json -o ./types --mode dtos

This is useful when you:

  • Only need the data models for a separate project
  • Want to share DTOs between multiple services
  • Are building a monorepo and need consistent type definitions
  • Want to generate TypeScript interfaces from your API spec
  • Need validated type definitions for frontend/backend sharing

DTO tests are generated by default in tests/dtos/ directory:

  • DTO specs: Test files with class-validator integration for validating DTOs
  • Tests ensure DTOs can be instantiated and properties are accessible

Example output:

generated/
├── dtos/
│   ├── user.dto.ts
│   └── post.dto.ts
├── users/
│   ├── users.service.ts
│   ├── users.controller.ts
│   └── users.module.ts
├── posts/
│   ├── posts.service.ts
│   ├── posts.controller.ts
│   └── posts.module.ts
└── tests/                           # 🧪 Test files with same structure
    ├── dtos/
    │   ├── user.dto.spec.ts
    │   └── post.dto.spec.ts
    ├── users/
    │   ├── users.controller.spec.ts
    │   └── users.service.spec.ts
    └── posts/
        ├── posts.controller.spec.ts
        └── posts.service.spec.ts

Generated File Structure

Server Mode (default) - With Tests & Validation

output/
├── index.ts                    # 🆕 Swagger setup helper function
├── app.module.ts              # Auto-generated/updated
├── dtos/
│   ├── user.dto.ts            # ✅ With validation decorators
│   ├── create-user-dto.dto.ts
│   ├── update-user-dto.dto.ts
│   ├── post.dto.ts
│   └── create-post-dto.dto.ts
├── users/
│   ├── users.service.ts
│   ├── users.controller.ts
│   └── users.module.ts
├── posts/
│   ├── posts.service.ts
│   ├── posts.controller.ts
│   └── posts.module.ts
└── tests/                     # 🧪 Generated by default
    ├── dtos/
    │   ├── user.dto.spec.ts
    │   ├── create-user-dto.dto.spec.ts
    │   └── ...
    ├── users/
    │   ├── users.controller.spec.ts
    │   └── users.service.spec.ts
    └── posts/
        ├── posts.controller.spec.ts
        └── posts.service.spec.ts

DTOs Mode (--mode dtos)

output/
├── dtos/
│   ├── user.dto.ts            # ✅ With validation decorators by default
│   ├── create-user-dto.dto.ts
│   ├── update-user-dto.dto.ts
│   ├── post.dto.ts
│   └── create-post-dto.dto.ts
├── tests/                     # 🧪 Generated by default
│   └── dtos/
│       ├── user.dto.spec.ts
│       ├── create-user-dto.dto.spec.ts
│       ├── update-user-dto.dto.spec.ts
│       ├── post.dto.spec.ts
│       └── create-post-dto.dto.spec.ts
└── index.ts                   # Barrel exports

Note: In dtos mode, only DTOs and their tests are generated. No services, controllers, modules, or Swagger config. Use --no-test to skip tests.

Client Mode

output/
├── dtos/
│   └── (same as server mode)
├── users/
│   └── users.client.ts
└── posts/
    └── posts.client.ts

Both Mode

output/
├── dtos/
│   └── (shared DTOs)
├── users/
│   ├── users.service.ts      # NestJS service
│   ├── users.controller.ts   # NestJS controller
│   ├── users.module.ts       # NestJS module
│   └── users.client.ts       # Client service (Axios)
└── posts/
    ├── posts.service.ts
    ├── posts.controller.ts
    ├── posts.module.ts
    └── posts.client.ts

Note: Service, controller, and module for each resource are grouped together in the same folder by tag name.

App Module Auto-Generation

When generating in server or both modes, the tool automatically creates or updates an app.module.ts file in the output directory that imports all generated feature modules.

Features:

  • Auto-creates app.module.ts if it doesn't exist
  • Auto-updates existing app.module.ts with all generated modules
  • Preserves custom imports (e.g., ConfigModule, DatabaseModule, etc.)
  • Updates module imports array automatically

Example Generated app.module.ts:

import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { PostsModule } from './posts/posts.module';

@Module({
  imports: [
    UsersModule,
    PostsModule
  ],
})
export class AppModule {}

With Custom Imports:

If your app.module.ts already has custom imports like ConfigModule, they will be preserved:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';  // ✅ Preserved
import { UsersModule } from './users/users.module';
import { PostsModule } from './posts/posts.module';

@Module({
  imports: [
    UsersModule,
    PostsModule
  ],
})
export class AppModule {}

Note: The generator will replace all feature module imports but preserve any custom third-party module imports you've added.

Swagger Setup (index.ts)

When generating in server or both modes, the tool automatically creates an index.ts file that exports a ready-to-use Swagger configuration function.

Features:

  • Auto-generates complete DocumentBuilder setup
  • Extracts metadata from OpenAPI spec (title, description, version)
  • Single function call to set up Swagger in your app
  • Customizable path for Swagger UI

Generated index.ts:

import { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

/**
 * Setup Swagger documentation for the NestJS application
 * @param app - The NestJS application instance
 * @param path - The path where Swagger UI will be available (default: 'api')
 */
export function setupSwagger(app: INestApplication, path: string = 'api') {
  const config = new DocumentBuilder()
    .setTitle('Example API')
    .setDescription('Example API for testing the code generator')
    .setVersion('1.0.0')
    .build();
  
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup(path, app, document);
}

Usage in main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { setupSwagger } from './generated';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // Setup Swagger documentation at /api
  setupSwagger(app);
  // Or custom path: setupSwagger(app, 'docs');
  
  await app.listen(3000);
  console.log('Swagger docs available at http://localhost:3000/api');
}
bootstrap();

Benefits:

  • No manual DocumentBuilder configuration needed
  • Metadata extracted from your OpenAPI spec
  • One-line Swagger setup in your application
  • Easy to customize or extend

Example

Input Swagger File (JSON)

{
  "swagger": "2.0",
  "info": { "title": "Example API", "version": "1.0.0" },
  "paths": {
    "/users": {
      "get": {
        "tags": ["users"],
        "summary": "Get all users",
        "responses": {
          "200": {
            "schema": {
              "type": "array",
              "items": { "$ref": "#/definitions/User" }
            }
          }
        }
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "required": ["id", "email"],
      "properties": {
        "id": { "type": "string" },
        "email": { "type": "string", "format": "email" }
      }
    }
  }
}

Input Swagger File (YAML)

swagger: '2.0'
info:
  title: Example API
  version: 1.0.0
paths:
  /users:
    get:
      tags:
        - users
      summary: Get all users
      responses:
        '200':
          schema:
            type: array
            items:
              $ref: '#/definitions/User'
definitions:
  User:
    type: object
    required:
      - id
      - email
    properties:
      id:
        type: string
      email:
        type: string
        format: email

Generated DTO

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

export class User {
  @ApiProperty({ description: 'User ID', type: String })
  id: string;

  @ApiProperty({ description: 'User email address', type: String })
  email: string;
}

Generated Controller

import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { UsersService } from '../services/users.service';

@ApiTags('users')
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @ApiOperation({ summary: 'Get all users' })
  @Get('')
  async getUsers(): Promise<any> {
    return this.usersService.getUsers();
  }
}

Generated Service

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  constructor() {}

  /**
   * Get all users
   */
  async getUsers(): Promise<any> {
    // TODO: Implement getUsers
    throw new Error('Method not implemented');
  }
}

Using Client Services

When generating in client or both mode, the tool creates TypeScript client services using Axios:

Generated Client Service

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { User } from '../dtos/user.dto';

export class UsersService {
  private axios: AxiosInstance;

  constructor(baseURL: string, config?: AxiosRequestConfig) {
    this.axios = axios.create({
      baseURL,
      ...config,
    });
  }

  /**
   * Get all users
   */
  async getUsers(): Promise<User[]> {
    const response = await this.axios.get(`/users`);
    return response.data;
  }

  /**
   * Get user by ID
   */
  async getUserById(id: string): Promise<User> {
    const response = await this.axios.get(`/users/${id}`);
    return response.data;
  }
}

Usage Example

import { UsersService } from './generated/users/users.client';

// Create service instance
const usersService = new UsersService('https://api.example.com', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});

// Use the service
async function fetchUsers() {
  try {
    const users = await usersService.getUsers();
    console.log('Users:', users);
    
    const user = await usersService.getUserById('123');
    console.log('User:', user);
  } catch (error) {
    console.error('Error:', error);
  }
}

Client Features

  • ✅ Automatic URL path parameter substitution
  • ✅ Query parameter support
  • ✅ Request body handling (POST, PUT, PATCH)
  • ✅ Typed responses using generated DTOs
  • ✅ Configurable Axios instance (headers, interceptors, etc.)

Development

Project Structure

src/
├── cli.ts                    # CLI entry point
├── generator.ts              # Main orchestrator
├── parser.ts                 # Swagger file parser
├── types.ts                  # TypeScript type definitions
├── utils.ts                  # Utility functions
├── file-writer.ts            # File writing utilities
└── generators/
    ├── dto.generator.ts      # DTO generation logic
    ├── service.generator.ts  # Service generation logic
    ├── controller.generator.ts # Controller generation logic
    └── module.generator.ts   # Module generation logic

Building

npm run build

Watching for Changes

npm run watch

Integration with NestJS Projects

After generating the code, you can integrate it into your NestJS project:

  1. Copy the generated files to your NestJS project's src directory
  2. Import the AppModule or individual feature modules in your main application module
  3. Implement the service methods with your business logic
  4. Add database integrations, validation pipes, guards, and interceptors as needed
// In your main.ts
import { AppModule } from './generated/app.module';

@Module({
  imports: [
    AppModule,
    // ... other modules
  ],
})
export class MainAppModule {}

📚 Documentation

📦 Version History

See CHANGELOG.md for detailed version history and RELEASE_NOTES.md for the latest release information.

License

MIT