⚑Auto-Sync OpenAPI to TypeScript in Real-Time

Sync Your APIEffortlessly

Automate TypeScript type generation, fully-typed API clients (Fetch, Axios, React Query, SWR, RTK Query), runtime validation schemas (Zod, Yup, Joi), endpoint definitions, and comprehensive documentation from your OpenAPI specifications. Keep your code in perfect sync with enterprise-grade reliability.

5.0.0
Latest Version
5
Client Types
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, fully-typed clients, and validation schemas perfectly synchronized with enterprise-grade reliability and developer-friendly features

API Client Generation

Generate fully-typed API clients and hooks for Fetch, Axios, React Query, SWR, and RTK Query with comprehensive inline documentation, ESLint compliance, and simplified Redux setup (v5.0.0).

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.

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.

5
Client Types

Fetch, Axios, React Query, SWR, RTK Query

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, fully-typed API clients, and validation schemasβ€”now with v5.0.0 improvements

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
100%
Open Source

Comprehensive Examples

Real-world examples covering all features: Interactive setup wizard, client generation (Fetch, Axios, React Query, SWR, RTK Query), validation schemas, real-time sync, folder splitting, and v5.0.0 improvements

Getting Started

Interactive Setup Wizard

Use the interactive wizard to configure your project (Recommended)

typescript
# Launch the interactive setup wizard
npx openapi-sync init

# The wizard will guide you through:
# βœ“ Configuration format (TypeScript/JSON/JavaScript)
# βœ“ API specification source (URL or local file)
# βœ“ Folder organization (split by tags automatically)
# βœ“ Client generation (Fetch, Axios, React Query, SWR, RTK Query)
# βœ“ Validation library (Zod, Yup, Joi)
# βœ“ Custom code preservation
# βœ“ Type naming preferences
# βœ“ Endpoint filtering
# βœ“ Documentation options

# Creates openapi.sync.ts with all your preferences
Getting Started

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"
  }
}

// Run sync command
// npx openapi-sync
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);
  }
}
Client Generation

Generate Fetch Client

Generate type-safe Fetch API client with ESLint compliance (v5.0.0)

typescript
# Generate Fetch client
npx openapi-sync generate-client --type fetch

# Usage
import apiClient from "./api/petstore/clients";

// Configure the client
apiClient.setApiConfig({
  baseURL: "https://api.example.com",
  headers: { Authorization: "Bearer token" },
});

// Make type-safe requests
const pet = await apiClient.getPetById({ 
  url: { petId: "123" } 
});
Client Generation

Generate Axios Client

Generate Axios-based API client with interceptors

typescript
# Generate Axios client
npx openapi-sync generate-client --type axios

# Usage
import apiClient from "./api/petstore/client";

apiClient.updateConfig({
  baseURL: "https://api.example.com",
  headers: {
    Authorization: "Bearer your-token",
  },
});

// Axios interceptors available
const response = await apiClient.getPetById({ 
  url: { petId: "123" } 
});
Client Generation

Generate React Query Hooks

Generate TanStack Query hooks for React applications

typescript
# Generate React Query hooks
npx openapi-sync generate-client --type react-query

# Usage in React component
import { useGetPetById, useCreatePet } from "./api/petstore/hooks";

function PetDetails({ petId }) {
  const { data, isLoading } = useGetPetById({
    url: { petId },
    query: { includeOwner: true },
  });

  const createPet = useCreatePet({
    onSuccess: () => console.log("Pet created!"),
  });

  return <div>{data?.name}</div>;
}
Client Generation

Generate SWR Hooks

Generate SWR hooks with comprehensive inline documentation (v5.0.0)

typescript
# Generate SWR hooks (230+ lines of inline docs)
npx openapi-sync generate-client --type swr

# Usage
import { useGetPetById, useCreatePet } from "./api/petstore/hooks";

function PetComponent({ petId }) {
  // GET request with SWR
  const { data, error, isLoading } = useGetPetById({
    url: { petId },
  });

  // Mutation with optimistic updates
  const { trigger } = useCreatePet({
    onSuccess: () => mutate("/pets"),
  });

  return <div>{data?.name}</div>;
}
Client Generation

Generate RTK Query API

Generate Redux Toolkit Query with simplified store setup (v5.0.0)

typescript
# Generate RTK Query API (with setupApiStore helper)
npx openapi-sync generate-client --type rtk-query

# Simplified Redux store setup (5 lines instead of 15!)
import { setupApiStore } from "./api/petstore/apis";

const store = configureStore({
  reducer: setupApiStore.reducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(setupApiStore.middleware),
});

// Use in components
import { useGetPetByIdQuery } from "./api/petstore/pets/apis";

function Pet({ petId }) {
  const { data } = useGetPetByIdQuery({ url: { petId } });
  return <div>{data?.name}</div>;
}
Client Generation

Client Generation with Filters

Generate clients for specific tags or endpoints

typescript
# Generate client for specific tags
npx openapi-sync generate-client --type fetch --tags pets,users

# Generate client for specific endpoints
npx openapi-sync generate-client \
  --type axios \
  --endpoints getPetById,createPet,updatePet

# Generate with custom output directory
npx openapi-sync generate-client \
  --type react-query \
  --output ./src/clients \
  --base-url https://api.example.com
Real-time Sync

Auto-Sync with Refetch Interval

Automatically sync API changes in development

typescript
// openapi.sync.json
{
  "refetchInterval": 5000,  // Sync every 5 seconds
  "folder": "./src/api",
  "api": {
    "petstore": "https://api.example.com/openapi.json"
  }
}

// Run in watch mode
// npx openapi-sync

// Output:
// βœ“ Syncing petstore...
// βœ“ Changes detected - regenerating types...
// βœ“ Generated 15 endpoints, 25 types
// ⏱ Next sync in 5 seconds...
Real-time Sync

Environment-Aware Sync

Different refetch intervals for different environments

typescript
// openapi.sync.ts
export default (): IConfig => {
  const isDev = process.env.NODE_ENV === "development";
  
  return {
    refetchInterval: isDev ? 5000 : 0,  // Only sync in dev
    folder: "./src/api",
    api: {
      myapi: isDev 
        ? "http://localhost:3000/openapi.json"
        : "https://api.example.com/openapi.json"
    }
  };
};
Folder Splitting

Organize by Tags (v5.0.0)

Automatic tag-based organization with streamlined setup

typescript
// openapi.sync.ts
const config: IConfig = {
  folder: "./src/api",
  api: {
    myapi: "https://api.example.com/openapi.json"
  },
  folderSplit: {
    byTags: true  // Auto-enabled in wizard!
  }
};

// Generated structure:
// api/
//   petstore/
//     pets/        ← Tag-based folder
//     users/       ← Tag-based folder
//     apis.ts      ← RTK Query aggregator (v5.0.0)
//     clients.ts   ← Fetch/Axios aggregator
//     hooks.ts     ← React Query/SWR aggregator
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

CLI Arguments Override Config

Command-line arguments now correctly override config file (v5.0.0)

typescript
# Config file specifies react-query, but CLI overrides
npx openapi-sync generate-client --type rtk-query

# Override base URL
npx openapi-sync generate-client \
  --type fetch \
  --base-url https://staging.api.example.com

# Override output directory
npx openapi-sync generate-client \
  --type axios \
  --output ./custom/path

# All CLI args now take precedence over config file!
Advanced

Multi-API Configuration

Manage multiple APIs in one project

typescript
// openapi.sync.ts
const config: IConfig = {
  folder: "./src/api",
  api: {
    "users": "https://users-api.example.com/openapi.json",
    "products": "https://products-api.example.com/openapi.json",
    "orders": "https://orders-api.example.com/openapi.json"
  },
  folderSplit: { byTags: true }
};

// Generate clients for specific API
// npx openapi-sync generate-client --type fetch --api users
// npx openapi-sync generate-client --type rtk-query --api products
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

Complete Configuration

Full configuration with all available options

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

const config: IConfig = {
  refetchInterval: 5000,
  folder: "./src/api",
  api: {
    petstore: "https://petstore3.swagger.io/api/v3/openapi.json"
  },
  
  // Client generation (v5.0.0)
  clientGeneration: {
    type: "react-query",
    baseURL: "https://api.example.com",
  },
  
  // Folder splitting
  folderSplit: { byTags: true },
  
  // Type naming
  types: {
    name: {
      prefix: "I",
      useOperationId: true,
    }
  },
  
  // Endpoint filtering
  endpoints: {
    exclude: { tags: ["deprecated"] },
    doc: { showCurl: true }
  },
  
  // Validation
  validations: {
    library: "zod",
    generate: { query: true, dto: true }
  }
};

export default config;
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);

Ready to Get Started?

Explore our comprehensive documentation for in-depth guides, API reference, troubleshooting tips, and advanced use cases. All examples are production-ready and include v5.0.0 improvements!

Ready to Sync Your API?

Join thousands of developers who have streamlined their API workflow with OpenAPI Sync. Generate types, fully-typed API clients, validation schemas, and comprehensive documentation in less than 5 minutesβ€”now with v5.0.0 improvements!

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