Auto-Sync OpenAPI to TypeScript in Real-Time

Sync Your APIEffortlessly

Automate TypeScript type generation, runtime validation schemas (Zod, Yup, Joi), endpoint definitions, and comprehensive documentation from your OpenAPI specifications. Keep your code in perfect sync.

4.0.0
Latest Version
10K+
Downloads
3
Validation Libraries
openapi.sync.json
{
  "refetchInterval": 5000,
  "folder": "./src/api",
  "api": {
    "petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
  },
  "validations": {
    "library": "zod"
  }
}

Powerful Features

Everything you need to keep your API documentation, TypeScript types, and validation schemas perfectly synchronized

🔥 Powerful Runtime Validation

Generate validation schemas using Zod, Yup, or Joi with full support for all OpenAPI data types, constraints, formats, and patterns.

Real-time Synchronization

Automatically fetches and syncs OpenAPI specifications from remote URLs with configurable refetch intervals.

TypeScript Type Generation

Generates TypeScript interfaces for all endpoints with support for complex nested objects, arrays, and unions.

Highly Configurable

Customize naming conventions, exclude/include endpoints, folder splitting, and URL transformations.

Enterprise Ready

Network error handling with exponential backoff, schema validation, and environment-aware auto-sync.

Rich Documentation

Generates comprehensive JSDoc comments with cURL examples, security schemes, and type references.

Folder Splitting

Organize generated code by tags, custom logic, or method-based splitting for better code organization.

Custom Code Preservation

Add your own custom code that survives regeneration with special comment markers.

3
Validation Libraries

Zod, Yup, and Joi - choose your favorite

100%
Type Safety

Full TypeScript support with comprehensive type definitions

Zero
Manual Work

Automated sync keeps everything up-to-date

Easy Installation

Get started in seconds with your favorite package manager. Generate types, validation schemas, and endpoints automatically.

terminal
$ npm install openapi-sync

📦Package Information

  • • Latest version: 4.0.0
  • • Bundle size: Optimized for production
  • • Dependencies: Minimal and well-maintained

Quick Start Guide

Get up and running in less than 5 minutes with full TypeScript types and validation schemas

01

Create Configuration

Create a configuration file in your project root

json
// openapi.sync.json
{
  "refetchInterval": 5000,
  "folder": "./src/api",
  "api": {
    "petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
  }
}
02

Run Sync Command

Execute the sync command to generate types and endpoints

bash
npx openapi-sync
03

Use Generated Code

Import and use the generated types and endpoints in your code

typescript
import { getPetById } from "./src/api/petstore/endpoints";
import { IPet } from "./src/api/petstore/types";

// Use the endpoint URL
const petUrl = getPetById("123"); // Returns: "/pet/123"

// Use the generated types
const pet: IPet = {
  id: 1,
  name: "Fluffy",
  status: "available"
};

What's Next?

📚

Explore Examples

Check out detailed examples for every use case

View Examples →
⚙️

Advanced Configuration

Learn about folder splitting, validation, and more

Read Docs →
💬

Get Support

Join our community or report issues

GitHub Issues →

Perfect For Every Use Case

Whether you're building backends, frontends, or microservices, OpenAPI Sync generates types, validation schemas, and endpoints for every use case

Backend API Development

Generate TypeScript types and validation schemas for your Node.js/Express backend. Ensure type safety across your entire API layer.

  • Request/Response type safety
  • Runtime validation with Zod/Yup/Joi
  • Automatic endpoint mapping

Frontend Applications

Keep your React, Vue, or Angular frontend in sync with your API. No more manual type definitions or outdated interfaces.

  • Auto-generated API client types
  • Form validation schemas
  • API endpoint constants

Microservices

Synchronize multiple microservices with their OpenAPI specs. Maintain consistent types across your entire service mesh.

  • Multi-API support
  • Service-specific configurations
  • Shared type definitions

Team Collaboration

Ensure everyone on your team works with the latest API definitions. Automated sync keeps all developers on the same page.

  • Git-friendly generated code
  • CI/CD integration
  • Custom code preservation

SDK Development

Build type-safe SDKs and client libraries for your APIs. Generate consistent interfaces for all your API consumers.

  • Client library scaffolding
  • Documentation generation
  • Version-specific types

Third-Party API Integration

Integrate external APIs with confidence. Generate types from public OpenAPI specs for popular services.

  • External API support
  • Type-safe integrations
  • Automatic updates

Trusted by Developers Worldwide

Join thousands of developers who have streamlined their API workflow

10K+
Downloads
500+
GitHub Stars
3
Validation Libraries
100%
Open Source

Comprehensive Examples

Real-world examples showing TypeScript generation, validation schemas, and endpoint synchronization

Basic Configuration

Simple Setup

Get started with a minimal configuration

typescript
// openapi.sync.json
{
  "refetchInterval": 5000,
  "folder": "./src/api",
  "api": {
    "petstore": "https://petstore3.swagger.io/api/v3/openapi.json"
  }
}
Validation Schemas

Zod Validation

Generate Zod schemas for runtime validation

typescript
// openapi.sync.ts
import { IConfig } from "openapi-sync/types";

const config: IConfig = {
  folder: "./src/api",
  api: {
    myapi: "https://api.example.com/openapi.json"
  },
  validations: {
    library: "zod",
    generate: {
      query: true,
      dto: true
    }
  }
};

export default config;
Validation Schemas

Using Generated Validation

Validate API requests with generated schemas

typescript
import { IAddPetDTOSchema } from "./src/api/petstore/validation";
import { z } from "zod";

// Validate request body
try {
  const validatedData = IAddPetDTOSchema.parse(req.body);
  // Data is now validated and typed
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error("Validation errors:", error.errors);
  }
}
Folder Splitting

Organize by Tags

Split generated code into folders based on API tags

typescript
// openapi.sync.ts
const config: IConfig = {
  folder: "./src/api",
  api: {
    myapi: "https://api.example.com/openapi.json"
  },
  folderSplit: {
    byTags: true  // Creates folders like admin/, user/, etc.
  }
};

export default config;
Folder Splitting

Custom Folder Logic

Use custom logic to determine folder structure

typescript
folderSplit: {
  customFolder: ({ method, path, tags }) => {
    // Admin endpoints
    if (tags?.includes("admin")) return "admin";
    
    // API versioning
    if (path.startsWith("/api/v1/")) return "v1";
    if (path.startsWith("/api/v2/")) return "v2";
    
    // Method-based organization
    if (method === "GET") return "read";
    if (method === "POST") return "create";
    
    return null; // Use default
  }
}
Endpoint Filtering

Exclude Endpoints

Filter out endpoints you don't need

typescript
endpoints: {
  exclude: {
    // Exclude by tags
    tags: ["deprecated", "internal"],
    
    // Exclude specific endpoints
    endpoints: [
      { path: "/admin/users", method: "DELETE" },
      { regex: "^/internal/.*", method: "GET" },
      { path: "/debug" }  // All methods
    ]
  }
}
Endpoint Filtering

Include Only Specific Endpoints

Generate code only for selected endpoints

typescript
endpoints: {
  include: {
    // Include only public endpoints
    tags: ["public"],
    
    // Include specific endpoints
    endpoints: [
      { path: "/public/users", method: "GET" },
      { regex: "^/public/.*" }
    ]
  }
}
Type Customization

Custom Type Names

Customize how types are named

typescript
types: {
  name: {
    prefix: "I",
    useOperationId: true,
    format: (source, data, defaultName) => {
      if (source === "shared") {
        return `${data.name}Type`;
      }
      if (source === "endpoint" && data.operationId) {
        return `${data.operationId}${data.type}`;
      }
      return defaultName;
    }
  }
}
Endpoint Configuration

Endpoint as Objects

Generate endpoints as objects with metadata

typescript
endpoints: {
  value: {
    type: "object",
    includeServer: true
  }
}

// Generated output:
export const getPetById = {
  method: "GET",
  operationId: "getPetById",
  url: (petId: string) => `/pet/${petId}`,
  tags: ["pet"]
};
Custom Code

Preserve Custom Code

Add custom code that survives regeneration

typescript
// endpoints.ts (after generation)
export const getPet = (petId: string) => `/pet/${petId}`;

// 🔒 CUSTOM CODE START
// Add your custom endpoints here
export const legacyGetPet = (id: string) => `/api/v1/pet/${id}`;

export const buildPetUrl = (petId: string, includePhotos: boolean) => {
  const base = getPet(petId);
  return includePhotos ? `${base}?include=photos` : base;
};
// 🔒 CUSTOM CODE END
Advanced

Multi-Environment Setup

Different configs for different environments

typescript
// openapi.sync.ts
export default (): IConfig => {
  const env = process.env.NODE_ENV || "development";
  
  const baseConfig: IConfig = {
    refetchInterval: env === "development" ? 5000 : 0,
    folder: "./src/api",
    api: {}
  };
  
  if (env === "development") {
    baseConfig.api = {
      "local": "http://localhost:3000/openapi.json"
    };
  } else {
    baseConfig.api = {
      "prod": "https://api.example.com/openapi.json"
    };
  }
  
  return baseConfig;
};
Advanced

Express Middleware Validation

Create validation middleware for Express

typescript
import { Request, Response, NextFunction } from "express";
import { z } from "zod";

export const validate = <T extends z.ZodTypeAny>(schema: T) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse(req.body);
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          error: "Validation failed",
          details: error.errors
        });
      }
    }
  };
};

// Usage
import { IAddPetDTOSchema } from "./api/validation";
router.post("/pet", validate(IAddPetDTOSchema), handler);

Need More Examples?

Check out our comprehensive documentation with detailed examples, best practices, and troubleshooting guides.

View Full Documentation

Ready to Sync Your API?

Join thousands of developers who have streamlined their API workflow with OpenAPI Sync. Generate types, validation schemas, and endpoints in less than 5 minutes.

Quick Start

npx openapi-sync

Lightning Fast

Generate thousands of types in seconds with optimized performance

🔒

Type Safe

100% TypeScript with full type safety and IntelliSense support

🎯

Zero Config

Works out of the box with sensible defaults, customize when needed