
OpenAPI Sync
OpenAPI Sync is a powerful developer tool that automates the synchronization of your API documentation with your codebase using OpenAPI (formerly Swagger) specifications. It generates TypeScript types, fully-typed API clients (Fetch, Next.js Fetch, Axios, React Query, SWR, RTK Query), endpoint definitions, runtime validation schemas (Zod, Yup, Joi), and comprehensive documentation from your OpenAPI schemaβensuring type safety from API specification through client implementation to runtime validation.
π Full documentation available at openapi-sync.com
Core Features
- β‘ Zero-Config Presets - 10 pre-configured framework presets (React Query, SWR, Axios, Fetch, RTK Query, Next.js, Python) for instant setup
- π Real-time API Synchronization - Automatically syncs OpenAPI specs from remote URLs with configurable intervals
- π Automatic Type Generation - Generates TypeScript interfaces for all endpoints with full nested support
- π Runtime Validation - Generate Zod, Yup, or Joi schemas from OpenAPI specs with all constraints preserved
- π― Interactive Setup Wizard - Streamlined configuration with auto-enabled tag-based folder splitting
- π‘οΈ Enterprise Ready - Error handling, validation, state persistence, and custom code preservation
- π¦ Folder Splitting - Organize code by tags or custom logic with aggregator files for easy imports
- π Rich Documentation - JSDoc comments with cURL examples and inline usage guides
- π€ Agent-Ready Endpoints - Browse endpoints with pagination and path filtering, inspect deep endpoint details, and read generated types without reloading the spec
- π©Ί Diagnostic Doctor - Diagnostic health checks for config validity, spec accessibility, peer dependencies, cache, and folder write permissions
- π§Ή Stale File Purge - Manifest-based stale code detection and cleanup with dry-run support to prevent orphaned code
- π Custom Code Injection - Preserve your custom code between regenerations with protected sections
View all features β
Installation
npm install openapi-sync
# or
npm install -g openapi-sync
# or use directly
npx openapi-sync
β οΈ macOS Big Sur Users: If you encounter an esbuild error (Symbol not found: _SecTrustCopyCertificateChain), install esbuild@0.17.19 first. See Troubleshooting for details.
π€ Using with AI Agents
All CLI commands and programmatic APIs are agent-safe β no interactive prompts, fully non-blocking. Use --json for machine-readable output and --silent to suppress logs.
Full agent reference: llms.txt β a structured discovery file for LLMs, Copilots, and MCP tools.
Agent Quick-Start (no prompts)
# 1. Create config (all settings as flags β no stdin required)
npx openapi-sync init --no-interactive \
--api-name petstore \
--api-url https://petstore3.swagger.io/api/v3/openapi.json \
--output-folder ./src/api \
--client-type react-query \
--validation-library zod \
--config-format typescript \
--json
# Or for protected specs, configure auth directly on init:
npx openapi-sync init --no-interactive \
--api-name backend \
--api-url https://api.example.com/openapi.json \
--auth-type bearer \
--auth-token '${env.SPEC_TOKEN}' \
--preset react-query-zod \
--json
# 2. Validate config + specs before writing any files
npx openapi-sync validate --json
# 3. Sync β generate types, endpoints, and schemas
npx openapi-sync --json
# 4. Generate a typed API client
npx openapi-sync generate-client --type react-query --json
Machine-Readable Output (--json)
Every command emits a single, pure JSON object to stdout when --json is passed, making it safe to pipe directly into jq or consume from automated agents. All human-readable progress logs are suppressed or directed to stderr.
$ npx openapi-sync --json
{
"success": true,
"apis": ["petstore"],
"filesWritten": ["src/api/petstore/types.ts", "src/api/petstore/endpoints.ts"],
"endpointCount": 20,
"warnings": [],
"errors": [],
"phases": {
"sync": { "filesWritten": ["src/api/petstore/types.ts", "src/api/petstore/endpoints.ts"], "endpointCount": 20 },
"client": { "filesWritten": [], "endpointCount": 20 }
}
}
$ npx openapi-sync validate --json
{
"valid": true,
"apis": { "petstore": { "valid": true, "endpointCount": 20 } },
"configErrors": []
}
$ npx openapi-sync list-endpoints --json
{
"petstore": [
{ "name": "getPetById", "method": "GET", "path": "/pet/{petId}", "tags": ["pet"], "summary": "Find pet by ID" },
{ "name": "addPet", "method": "POST", "path": "/pet", "tags": ["pet"], "summary": "Add a new pet" }
]
}
$ npx openapi-sync list-endpoints --api petstore --path-contains pet --limit 2 --offset 0 --json
$ npx openapi-sync get-endpoint --api petstore --operation-id getPetById --json
$ npx openapi-sync read-type --api petstore --type-name Pet --json
Dry Run (preview without writing files)
Compact, fast previews of planned files:
npx openapi-sync --dry-run --json
npx openapi-sync generate-client --type fetch --dry-run --json
Layouts & Output Directories
- Flat Mode (Default): When
folderSplit is omitted or empty ({}), files are placed directly in the API folder (endpoints.ts, types/index.ts, types/shared.ts).
- Tag-Split Mode: Setting
folderSplit: { byTags: true } organizes endpoints into tag subfolders (e.g. {tag}/endpoints.ts, {tag}/types.ts, shared.ts).
- Custom Client Directory:
clientGeneration.outputDir (or CLI --output) is fully supported in both flat and folder-split layouts. In flat mode, clients are placed directly in {outputDir}/clients.ts (or api.ts), while in folder-split mode clients are placed in {outputDir}/{tag}/client.ts and aggregated at {outputDir}/clients.ts, with relative imports resolving back to your generated types and endpoints.
Programmatic API (TypeScript)
import {
ValidateConfig,
Init,
GenerateClient,
ListEndpoints,
GetEndpointDetails,
ReadGeneratedType,
Doctor,
Purge,
} from "openapi-sync";
// Pre-flight check β no files written
const validation = await ValidateConfig({ silent: true });
if (!validation.valid) throw new Error(JSON.stringify(validation));
// Diagnostic health check on config, specs, peer dependencies, and directories
const health = await Doctor({ silent: true });
console.log("Health check:", health.healthy ? "All checks passed" : "Issues detected");
// Inspect API surface with pagination and filtering
const endpoints = await ListEndpoints({
apiName: "petstore",
pathContains: "pet",
limit: 5,
offset: 0,
silent: true,
});
console.log(endpoints.petstore.length, "endpoints found");
// Inspect a single endpoint in full detail (4-tier fuzzy matching)
const detail = await GetEndpointDetails({ apiName: "petstore", operationId: "getPetById", silent: true });
console.log(detail.endpoint.path);
// Read an exact generated type declaration (with optional line pagination)
const typeDecl = await ReadGeneratedType({ apiName: "petstore", typeName: "Pet", silent: true });
console.log(typeDecl);
// Sync and get structured result
const syncResult = await Init({ silent: true });
if (!syncResult.success) throw new Error(JSON.stringify(syncResult));
console.log("Files written:", syncResult.filesWritten);
// Generate client
const clientResult = await GenerateClient({ type: "react-query", silent: true });
console.log(JSON.stringify(clientResult));
// Detect and purge stale files from disk
const purgeResult = await Purge({ yes: true, silent: true });
console.log("Purged files:", purgeResult.purged);
Exit Codes
| Code | Meaning |
|---|
0 | Success |
1 | Config error or validation failed |
2 | Network / spec fetch error |
3 | Generation / file write error |
Agent-safe vs Interactive Commands
| Command | Agent-safe? | Description |
|---|
npx openapi-sync | β
| Sync specs, generate types, endpoints, schemas |
npx openapi-sync validate | β
| Validate config + specs; no files written |
npx openapi-sync doctor | β
| Diagnostic health check on config, network, peer deps, cache |
npx openapi-sync list-endpoints | β
| List endpoints with filtering and pagination; no files written |
npx openapi-sync get-endpoint | β
| Inspect detailed schema for one endpoint by operationId or name |
npx openapi-sync read-type | β
| Read generated TypeScript declaration block |
npx openapi-sync generate-client | β
| Generate typed API client (fetch, next-fetch, axios, react-query, swr, rtk-query) |
npx openapi-sync purge --yes | β
| Remove stale generated files without prompting |
npx openapi-sync init --no-interactive | β
| Create config file without prompts |
npx openapi-sync init (no flag) | β | Interactive wizard (requires stdin) |
Quick Start
Option 1: Interactive Setup (Recommended) π―
The easiest way to get started is with the interactive setup wizard:
The wizard will guide you through: