# openapi-sync A CLI + Node.js library that generates TypeScript types, fully-typed API clients, and runtime validation schemas from OpenAPI (Swagger) specifications. Supports: TypeScript, Python, Fetch, Axios, React Query, SWR, RTK Query, Zod, Yup, Joi. npm: https://www.npmjs.com/package/openapi-sync Docs: https://openapi-sync.com GitHub: https://github.com/akintomiwa-fisayo/openapi-sync ## AGENT QUICK-START Minimum working setup (no interactive prompts needed): ```bash # 1. Create config (agent-safe, no prompts) npx openapi-sync init --no-interactive \ --api-name petstore \ --api-url https://petstore3.swagger.io/api/v3/openapi.json \ --output-folder ./src/api \ --config-format typescript # 2. Validate config and spec before writing any files npx openapi-sync validate --json # 3. Sync — generates types, endpoints, validation schemas npx openapi-sync --json # 4. (Optional) generate a typed API client npx openapi-sync generate-client --type react-query --json ``` All commands support `--json` (machine-readable stdout) and exit codes: 0 = success | 1 = config/validation error | 2 = network error | 3 = generation error ## CLI COMMANDS ### Agent-safe commands (no stdin required) | Command | Description | |---------|-------------| | `npx openapi-sync` | Sync specs, generate types + endpoints + schemas, and record `.openapi-sync/lock.json` + snapshot | | `npx openapi-sync --frozen` | Verify specs match `.openapi-sync/lock.json` and fail without writing if drifted | | `npx openapi-sync --use-snapshot` | Generate deterministically from `.openapi-sync/snapshots/.json` | | `npx openapi-sync validate` | Validate config + specs; supports `--frozen`, `--use-snapshot`, `--fail-on-breaking` | | `npx openapi-sync diff` | Diff specs against `.openapi-sync/snapshots/` (or `--from`/`--to`); supports `--fail-on-breaking` | | `npx openapi-sync doctor` | Run diagnostic health check on config, network, peer deps, cache | | `npx openapi-sync list-endpoints` | List endpoints from a spec with optional filters/pagination; no files written | | `npx openapi-sync get-endpoint` | Inspect one endpoint in full detail by operationId or name | | `npx openapi-sync read-type` | Read one generated TypeScript interface/type declaration | | `npx openapi-sync generate-client --type ` | Generate typed API client | | `npx openapi-sync purge --yes` | Detect and remove stale generated files without prompts | | `npx openapi-sync init --no-interactive [FLAGS]` | Create config file without prompts | ### Model Context Protocol (MCP) Server Run via `npx openapi-sync-mcp` or `openapi-sync-mcp`. Exposes 11 tools for AI agents: 1. `openapi_sync_validate`: Validate config & specs without writing files (supports `frozen`, `useSnapshot`, `failOnBreaking`, auth, and config overrides). 2. `openapi_sync_diff`: Compare specs against `.openapi-sync/snapshots/` (or `from`/`to`) and flag breaking contract changes. 3. `openapi_sync_doctor`: Run full diagnostic health checks and return structured reports. 4. `openapi_sync_list_endpoints`: List all endpoints with optional tag/path filters and pagination. 5. `openapi_sync_get_endpoint_details`: Retrieve full parameter and response schemas for a specific endpoint. 6. `openapi_sync_read_generated_type`: Read exact TypeScript declarations with optional `offset`/`maxLines` pagination. 7. `openapi_sync_sync`: Run full sync generation (supports `frozen` and `useSnapshot`). 8. `openapi_sync_generate_client`: Generate typed Fetch/Next Fetch/Axios/React Query/SWR/RTK Query clients (supports `frozen` and `useSnapshot`). 9. `openapi_sync_init`: Create typed openapi.sync configuration without user prompts (default output folder: project root `""`). 10. `openapi_sync_purge`: Detect and remove stale generated files (supports `dryRun` and `yes`). 11. `openapi_sync_read_config`: Inspect active configuration file content. ### Interactive-only (requires human stdin — NOT safe for agents) | Command | Description | |---------|-------------| | `npx openapi-sync init` | Interactive wizard | ### Global flags (all commands) | Flag | Description | |------|-------------| | `--json` | Emit a single JSON object to stdout; suppress emoji logs | | `--silent` | Suppress all console output | | `--dry-run` | Show what would be written without writing (sync, generate-client) | | `--help, -h` | Help | | `--version, -v` | Version | ### `init` flags (used with `--no-interactive`) | Flag | Default | Description | |------|---------|-------------| | `--api-name` | `"myapi"` | API key in config | | `--api-url` | — | URL to OpenAPI spec | | `--api-file` | — | Path to local spec file | | `--output-folder` | `""` (project root) | Generated files output (alias: `--folder`, `-f`) | | `--config-format` | `"typescript"` | `typescript`, `json`, `javascript` | | `--client-type` | — | `react-query`, `swr`, `fetch`, `axios`, `rtk-query` | | `--validation-library` | — | `zod`, `yup`, `joi` (alias: `--validation-lib`) | | `--folder-split` | `false` | Organise by OpenAPI tags (alias: `--split-by-tags`) | | `--types-prefix` | `"I"` | TS interface name prefix (alias: `--type-prefix`) | | `--use-operation-id` | `true` | Use operationId for names | | `--exclude-tags` | — | Comma-separated tags to exclude | | `--show-curl` | `false` | Include cURL in JSDoc | | `--refetch-interval` | `0` | Auto-refetch ms (0=disabled) | | `--run-sync` | `false` | Run sync after config creation | | `--auth-type` | — | Authentication type (`bearer`, `basic`, `apiKey`, `custom`) | | `--auth-token` | — | Bearer token / password / auth value | | `--auth-username` | — | Username for basic auth | | `--auth-password` | — | Password for basic auth | | `--auth-name` | `"X-API-Key"` | Header or query parameter name for API key | | `--auth-value` | — | API key value | | `--auth-in` | `"header"` | API key location (`header` or `query`) | | `--auth-header` | — | Custom header string (`Key: Value`) | ### `generate-client` flags | Flag | Alias | Description | |------|-------|-------------| | `--type` | `-t` | Client type (`fetch`, `next-fetch`, `axios`, `react-query`, `swr`, `rtk-query`) (required) | | `--api` | `-a` | Specific API from config | | `--tags` | | Filter endpoints by tags | | `--endpoints` | `-e` | Filter by endpoint names | | `--output` | `-o` | Output directory | | `--base-url` | `-b` | Base URL baked into client | ### `list-endpoints` flags | Flag | Description | |------|-------------| | `--api` | Limit to a specific API | | `--tags` | Comma-separated tag filter | | `--limit` | Maximum number of endpoints to return | | `--offset` | Pagination offset | | `--path-contains` | Filter endpoints by path substring | | `--use-cache` | Reuse cached endpoints when available | ### `generate-client` flags | Flag | Description | |------|-------------| | `--use-cache` | Reuse cached endpoints instead of reloading the spec | ### `get-endpoint` flags | Flag | Description | |------|-------------| | `--api` | Limit to a specific API | | `--operation-id` | Find the endpoint by operationId | | `--name` | Find the endpoint by endpoint name | ### `read-type` flags | Flag | Description | |------|-------------| | `--api` | API name from the config | | `--type-name` | Exported interface/type name to read | ### `purge` flags | Flag | Alias | Description | |------|-------|-------------| | `--yes` | `-y` | Delete stale files without confirmation prompt | | `--dry-run` | | Preview which files would be deleted | | `--api` | `-a` | Limit purge check to a specific API | ### Zero-Config CLI Execution (No config file on disk needed) AI agents can run `openapi-sync` immediately without creating a configuration file: ```bash # Sync with preset and direct spec URL npx openapi-sync --api-url https://petstore3.swagger.io/api/v3/openapi.json --preset react-query-zod --folder ./src/api --json # Protected spec via CLI auth flags npx openapi-sync --api-url https://api.example.com/openapi.json --auth-type bearer --auth-token "$TOKEN" --preset next-fetch --json # Multiple APIs inline npx openapi-sync --api users=https://api.example.com/users.json --api billing=https://api.example.com/billing.json --preset axios-zod --json # Full inline JSON config npx openapi-sync --config-json '{"api":{"main":"https://api.example.com/spec.json"},"preset":"react-query-zod"}' --json ``` ## MCP TOOLS OpenAPI Sync also ships a built-in MCP server (`npx openapi-sync-mcp`) for agent workflows. Long-running MCP calls reuse cached endpoints by default when available. - `openapi_sync_read_config` - `openapi_sync_validate` (supports `frozen`, `useSnapshot`, `failOnBreaking`, auth & config overrides) - `openapi_sync_diff` (diff specs against `.openapi-sync/snapshots/` or `from`/`to`, classify breaking changes) - `openapi_sync_doctor` - `openapi_sync_list_endpoints` (supports pagination, path filters, auth, and `useCache`) - `openapi_sync_get_endpoint_details` - `openapi_sync_read_generated_type` - `openapi_sync_sync` (supports `frozen`, `useSnapshot`) - `openapi_sync_generate_client` (supports `next-fetch`, `dryRun`, `verbose`, `frozen`, `useSnapshot`, tags, endpoints, outputDir, baseUrl) - `openapi_sync_purge` (supports `dryRun` and `yes`) - `openapi_sync_init` (first-class auth, `runSync`, default folder `""`) ## PROGRAMMATIC API All functions are exported from the `openapi-sync` package for both ESM and CJS: ```typescript import { Init, // Sync specs → types, endpoints, schemas (supports frozen, useSnapshot) GenerateClient, // Generate typed API client (supports frozen, useSnapshot) ValidateConfig, // Pre-flight check (supports frozen, useSnapshot, failOnBreaking) DiffSpecs, // Compare specs vs snapshots or from/to & classify breaking changes Doctor, // Diagnostic health checks Purge, // Detect and clean stale generated files ListEndpoints, // Inspect API surface (no file writes) GetEndpointDetails, // Read one endpoint in full detail ReadGeneratedType, // Read one generated TypeScript declaration InteractiveInit, // NOT agent-safe — requires stdin } from "openapi-sync"; ``` ### Doctor(options?) → Promise Agent-safe. Checks configuration, network access, peer dependencies, and cache. ```typescript const report = await Doctor({ silent: true }); // report: { healthy: boolean, checks: DoctorCheckItem[], recommendations: string[] } ``` ### Init(options?) → Promise Agent-safe. Returns SyncResult. ```typescript const result = await Init({ silent: true }); // result: { success, apis, filesWritten, endpointCount, warnings, errors } ``` ### GenerateClient(options) → Promise Agent-safe. Syncs then generates a typed client. ```typescript const result = await GenerateClient({ type: "react-query", // "fetch"|"axios"|"react-query"|"swr"|"rtk-query" apiName: "petstore", // optional; defaults to all APIs baseURL: "https://api.example.com", tags: ["pets"], // optional tag filter silent: true, }); ``` ### ValidateConfig(options?) → Promise Agent-safe. No files written. ```typescript const validation = await ValidateConfig({ silent: true }); // validation: { valid, apis: { [name]: { valid, endpointCount, error? } }, configErrors } if (!validation.valid) process.exit(1); ``` ### ListEndpoints(options?) → Promise> Agent-safe. No files written. ```typescript const map = await ListEndpoints({ apiName: "petstore", tags: ["pet"], limit: 10, offset: 0, pathContains: "pet", useCache: true, }); // map: { petstore: [{ name, method, path, operationId, tags, summary }] } ``` ### GetEndpointDetails(options?) → Promise<{ apiName: string; endpoint: EndpointSummary & Record }> Agent-safe. No files written. ```typescript const detail = await GetEndpointDetails({ apiName: "petstore", operationId: "getPetById" }); ``` ### ReadGeneratedType(options) → Promise Agent-safe. Returns the matched generated declaration block. ```typescript const declaration = await ReadGeneratedType({ apiName: "petstore", typeName: "Pet" }); ``` ### Purge(options?) → Promise<{ success: boolean; purged: string[]; message?: string }> Agent-safe. Compares disk files against manifest and deletes orphaned code. ```typescript const purgeReport = await Purge({ yes: true, silent: true }); // purgeReport: { success: true, purged: ["src/api/petstore/deleted_endpoint.ts"] } ``` ### InteractiveInit() → Promise NOT agent-safe — blocks on stdin prompts. Use CLI `init --no-interactive` instead. ## CONFIG FILE FORMAT Config file: `openapi.sync.ts` | `openapi.sync.js` | `openapi.sync.json` JSON Schema: https://openapi-sync.com/schema/openapi.sync.schema.json ### Minimal config ```json { "folder": "./src/api", "api": { "petstore": "https://petstore3.swagger.io/api/v3/openapi.json" } } ``` ### Full TypeScript config ```typescript import { IConfig } from "openapi-sync"; const config: IConfig = { folder: "./src/api", api: { petstore: "https://petstore3.swagger.io/api/v3/openapi.json" }, refetchInterval: 5000, language: "typescript", // "typescript" | "python" folderSplit: { byTags: true }, types: { name: { prefix: "I", useOperationId: true } }, endpoints: { value: { type: "string" }, // "string" | "object" doc: { showCurl: true }, exclude: { tags: ["deprecated"] }, }, validations: { library: "zod" }, // "zod" | "yup" | "joi" clientGeneration: { enabled: true, type: "react-query", // "fetch"|"next-fetch"|"axios"|"react-query"|"swr"|"rtk-query" baseURL: "https://api.example.com", reactQuery: { version: 5, mutations: true }, }, customCode: { enabled: true, position: "bottom" }, }; export default config; ``` ### Key IConfig fields | Field | Type | Description | |-------|------|-------------| | `api` | `Record` | **Required.** Map of API name → spec URL or file path | | `folder` | `string` | Output folder (default: `""` project root) | | `language` | `"typescript"\|"python"` | Output language | | `refetchInterval` | `number` | Auto-refetch ms | | `folderSplit.byTags` | `boolean` | Split output by OpenAPI tags | | `validations.library` | `"zod"\|"yup"\|"joi"` | Validation schema library | | `endpoints.value.type` | `"string"\|"object"` | Endpoint export format (`"string"` URL/builder or `"object"` metadata `{ method, operationId, url, tags }`; all client types auto-resolve `.url`) | | `endpoints.sharedPaths` | `boolean` | Extract shared URL path helpers and `BASE_URL` in `endpoints.ts` | | `clientGeneration.type` | string | Client type to generate (`fetch`, `next-fetch`, `axios`, `react-query`, `swr`, `rtk-query`) | | `clientGeneration.baseURL` | `string \| Record` | Base URL (or per-API map) for generated client | | `clientGeneration.returnType` | `string \| { overrides?: Record; format?: Function }` | Custom return type: template string (`"${type} \| undefined"`), overrides map, or formatter | | `endpoints.exclude.tags` | `string[]` | Tags to exclude from generation | ### Protected Specs & Stored Auth (`auth`) Protected OpenAPI specs can be fetched using Bearer tokens, Basic auth, API keys, or custom headers. > ⚠️ **CRITICAL INSTRUCTION FOR AI AGENTS & HUMANS:** > Whenever authentication credentials or environment variables are needed, you **MUST use a TypeScript (`openapi.sync.ts`) or JavaScript (`openapi.sync.js`) config file** (`--config-format typescript`). > **DO NOT write `process.env.VAR` inside a static `openapi.sync.json` file** — JSON does not evaluate JavaScript and will fail with a JSON parse error. ```typescript // openapi.sync.ts import { defineConfig } from "openapi-sync"; export default defineConfig({ api: { protectedApi: { url: "https://api.example.com/openapi.json", auth: { type: "bearer", token: process.env.MY_API_TOKEN!, // safe, dynamic, never hardcoded }, }, }, }); ``` ## STRUCTURED RETURN TYPES ### SyncResult (returned by Init, GenerateClient) ```typescript type SyncResult = { success: boolean; apis: string[]; filesWritten: string[]; endpointCount: number; warnings: string[]; errors: string[]; }; ``` ### ValidationResult (returned by ValidateConfig) ```typescript type ValidationResult = { valid: boolean; apis: Record; configErrors: string[]; }; ``` ### EndpointSummary (items in ListEndpoints result) ```typescript type EndpointSummary = { name: string; method: string; path: string; operationId?: string; tags?: string[]; summary?: string; }; ``` ## GENERATED FILE STRUCTURE ``` ./src/api/ {apiName}/ types.ts ← TypeScript interfaces for all schemas endpoints.ts ← Typed endpoint URL builder functions shared.ts ← Shared component types validations.ts ← Zod/Yup/Joi schemas (if enabled) client/ client.ts ← Fetch/Axios client instance hooks.ts ← React Query / SWR hooks (if enabled) ``` When `folderSplit.byTags` is true, types/endpoints/validations are split into tag-named subdirectories (`{tag}/endpoints.ts`, `{tag}/types.ts`, `shared.ts`). When `folderSplit` is omitted or empty (`{}`), generation defaults to flat mode (`endpoints.ts`, `types/index.ts`, `types/shared.ts`). Custom `clientGeneration.outputDir` (or CLI `--output`) is fully supported in both flat and folder-split layouts, with automatic relative import resolution back to generated types and endpoints. ## ERROR CODES (typed errors) | Code | Class | Trigger | |------|-------|---------| | `CONFIG_NOT_FOUND` | ConfigNotFoundError | No config file in cwd | | `CONFIG_PARSE_FAILED` | ConfigParseError | Config file parse error | | `CONFIG_INVALID` | ConfigValidationError | Bad config field value | | `SPEC_FETCH_FAILED` | SpecFetchError | Network error fetching spec | | `SPEC_READ_FAILED` | SpecReadError | Local file read error | | `SPEC_PARSE_FAILED` | SpecParseError | Not a valid OpenAPI spec | | `GENERATION_FAILED` | GenerationError | File write error | | `UNKNOWN_API` | UnknownApiError | API name not in config | | `SPEC_PIN_MISMATCH` | SpecPinMismatchError | Spec differs from pinned `version`, `sha256`, or `.openapi-sync/lock.json` | | `SPEC_LOCK_MISSING` | SpecLockNotFoundError | Missing lock entry or snapshot for `--frozen` / `--use-snapshot` | | `BREAKING_SPEC_CHANGE` | BreakingSpecChangeError | Breaking contract change detected with `--fail-on-breaking` | All error classes extend `OpenApiSyncError` and expose `.code`, `.message`, and `.toJSON()`. ## CI/CD SPEC PINNING & BREAKING-CHANGE CHECKS Recommended workflow: commit generated files + `.openapi-sync/lock.json` + `.openapi-sync/snapshots/`, run `npx openapi-sync` inside PRs for contract review (rather than regenerating from a floating `latest` URL during production builds), and gate CI with: ```bash npx openapi-sync validate --frozen --json npx openapi-sync diff --fail-on-breaking --json npx openapi-sync --use-snapshot --json ``` ## COMMON AGENT WORKFLOWS ### Workflow 1: First-time setup ```bash # Public spec: npx openapi-sync init --no-interactive \ --api-name myapi \ --api-url https://api.example.com/openapi.json \ --output-folder ./src/api \ --client-type react-query \ --validation-library zod \ --config-format typescript \ --json # Protected spec (configure auth directly on init to prevent 401): npx openapi-sync init --no-interactive \ --api-name myapi \ --api-url https://api.example.com/openapi.json \ --output-folder ./src/api \ --client-type react-query \ --validation-library zod \ --config-format typescript \ --auth-type bearer \ --auth-token '${env.SPEC_TOKEN}' \ --json npx openapi-sync validate --json npx openapi-sync --json npx openapi-sync generate-client --type react-query --json ``` ### Workflow 2: Inspect before generating ```bash # See what endpoints exist before committing to a client type npx openapi-sync list-endpoints --json | jq '.petstore | map(.method + " " + .path)' # Preview what would be written npx openapi-sync --dry-run --json npx openapi-sync generate-client --type fetch --dry-run --json ``` ### Workflow 3: Programmatic (TypeScript) ```typescript import { ValidateConfig, Init, GenerateClient } from "openapi-sync"; const validation = await ValidateConfig({ silent: true }); if (!validation.valid) throw new Error(JSON.stringify(validation)); const syncResult = await Init({ silent: true }); if (!syncResult.success) throw new Error(JSON.stringify(syncResult)); const clientResult = await GenerateClient({ type: "axios", silent: true }); console.log(JSON.stringify(clientResult)); ``` ### Workflow 4: Diagnostic health check & stale file cleanup ```bash # 1. Diagnose environment and spec reachability npx openapi-sync doctor --json # 2. Preview any stale files before removal npx openapi-sync purge --dry-run --json # 3. Clean up stale files safely npx openapi-sync purge --yes --json ```