orval

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Orval - OpenAPI to TypeScript Code Generator

Orval - OpenAPI转TypeScript代码生成器

Orval generates type-safe TypeScript clients, hooks, schemas, mocks, and server handlers from OpenAPI v3/Swagger v2 specifications.
Orval 可从 OpenAPI v3/Swagger v2 规范生成类型安全的 TypeScript 客户端、钩子、模式、模拟以及服务器处理器。

Quick Start

快速开始

Installation

安装

bash
npm install orval -D
bash
npm install orval -D

or yarn add orval -D

or yarn add orval -D

or pnpm add orval -D

or pnpm add orval -D

or bun add orval -D

or bun add orval -D

undefined
undefined

Minimal Configuration

最简配置

ts
import { defineConfig } from 'orval';

export default defineConfig({
  petstore: {
    input: {
      target: './petstore.yaml',
    },
    output: {
      target: './src/api/petstore.ts',
      schemas: './src/api/model',
      client: 'react-query',
    },
  },
});
ts
import { defineConfig } from 'orval';

export default defineConfig({
  petstore: {
    input: {
      target: './petstore.yaml',
    },
    output: {
      target: './src/api/petstore.ts',
      schemas: './src/api/model',
      client: 'react-query',
    },
  },
});

Run

运行

bash
npx orval
npx orval --config ./orval.config.ts
npx orval --project petstore
npx orval --watch
bash
npx orval
npx orval --config ./orval.config.ts
npx orval --project petstore
npx orval --watch

Choosing Your Setup

选择你的配置方案

Client Selection Guide

客户端选择指南

Use CaseClienthttpClientNotes
React with server state
react-query
fetch
or
axios
TanStack Query hooks
Vue 3 with server state
vue-query
fetch
or
axios
TanStack Query for Vue
Svelte with server state
svelte-query
fetch
or
axios
TanStack Query for Svelte
SolidJS standalone app
solid-query
fetch
or
axios
TanStack Query for Solid
SolidStart full-stack
solid-start
native fetchUses
query()
/
action()
primitives
Angular with signals
angular-query
angular
Injectable functions, signal reactivity
Angular traditional
angular
HttpClient services
React with SWR
swr
fetch
or
axios
Vercel SWR hooks
Lightweight / Edge
fetch
Zero dependencies, works everywhere
Node.js / existing Axios
axios-functions
Factory functions (default)
Axios with DI
axios
Injectable Axios instance
Validation only
zod
Zod schemas, no HTTP client
Backend API server
hono
Hono handlers with Zod validation
AI agent tools
mcp
Model Context Protocol servers
使用场景客户端httpClient说明
React 服务端状态管理
react-query
fetch
axios
TanStack Query 钩子
Vue 3 服务端状态管理
vue-query
fetch
axios
Vue 版 TanStack Query
Svelte 服务端状态管理
svelte-query
fetch
axios
Svelte 版 TanStack Query
SolidJS 独立应用
solid-query
fetch
axios
Solid 版 TanStack Query
SolidStart 全栈应用
solid-start
原生 fetch使用
query()
/
action()
原语
Angular 信号式状态管理
angular-query
angular
可注入函数、信号响应式
传统 Angular 应用
angular
HttpClient 服务
React 搭配 SWR
swr
fetch
axios
Vercel SWR 钩子
轻量/边缘环境
fetch
零依赖,支持所有环境
Node.js / 已有 Axios 环境
axios-functions
工厂函数(默认)
依赖注入式 Axios
axios
可注入的 Axios 实例
仅需验证
zod
Zod 模式,无 HTTP 客户端
后端 API 服务器
hono
带 Zod 验证的 Hono 处理器
AI Agent 工具
mcp
模型上下文协议(Model Context Protocol)服务器

Mode Selection Guide

模式选择指南

  • single
    — Everything in one file. Best for small APIs.
  • split
    — Separate files:
    petstore.ts
    ,
    petstore.schemas.ts
    ,
    petstore.msw.ts
    . Good for medium APIs.
  • tags
    — One file per OpenAPI tag + shared schemas. Organizes by domain.
  • tags-split
    — Folder per tag with split files. Best for large APIs. Recommended.
  • single
    — 所有内容生成在一个文件中。适合小型 API。
  • split
    — 拆分到多个文件:
    petstore.ts
    petstore.schemas.ts
    petstore.msw.ts
    。适合中型 API。
  • tags
    — 每个 OpenAPI 标签对应一个文件 + 共享模式。按领域组织代码。
  • tags-split
    — 每个标签对应一个文件夹,内部拆分文件。适合大型 API。推荐使用。

httpClient Option

httpClient 选项

For
react-query
,
vue-query
,
svelte-query
, and
swr
clients:
ts
output: {
  client: 'react-query',
  httpClient: 'fetch',  // 'fetch' (default) | 'axios'
}
For
angular-query
:
ts
output: {
  client: 'angular-query',
  httpClient: 'angular',  // Uses Angular HttpClient
}
对于
react-query
vue-query
svelte-query
swr
客户端:
ts
output: {
  client: 'react-query',
  httpClient: 'fetch',  // 'fetch' (默认) | 'axios'
}
对于
angular-query
ts
output: {
  client: 'angular-query',
  httpClient: 'angular',  // 使用 Angular HttpClient
}

Configuration Reference

配置参考

Config Structure

配置结构

ts
import { defineConfig } from 'orval';

export default defineConfig({
  [projectName]: {
    input: InputOptions,
    output: OutputOptions,
    hooks: HooksOptions,
  },
});
Multiple projects can share the same config file with different input/output settings.
ts
import { defineConfig } from 'orval';

export default defineConfig({
  [projectName]: {
    input: InputOptions,
    output: OutputOptions,
    hooks: HooksOptions,
  },
});
多个项目可共享同一个配置文件,使用不同的输入/输出设置。

Input Options

输入选项

ts
input: {
  target: './spec.yaml',              // Path or URL to OpenAPI spec (required)
  override: {
    transformer: './transform.js',    // Transform spec before generation
  },
  filters: {
    mode: 'include',                  // 'include' | 'exclude'
    tags: ['pets', /health/],         // Filter by OpenAPI tags
    schemas: ['Pet', /Error/],        // Filter by schema names
  },
  parserOptions: {
    headers: [                        // Auth headers for remote spec URLs
      {
        domains: ['api.example.com'],
        headers: {
          Authorization: 'Bearer YOUR_TOKEN',
          'X-API-Key': 'your-api-key',
        },
      },
    ],
  },
}
ts
input: {
  target: './spec.yaml',              // OpenAPI 规范的路径或 URL(必填)
  override: {
    transformer: './transform.js',    // 生成前转换规范
  },
  filters: {
    mode: 'include',                  // 'include' | 'exclude'
    tags: ['pets', /health/],         // 按 OpenAPI 标签过滤
    schemas: ['Pet', /Error/],        // 按模式名称过滤
  },
  parserOptions: {
    headers: [                        // 远程规范 URL 的认证头
      {
        domains: ['api.example.com'],
        headers: {
          Authorization: 'Bearer YOUR_TOKEN',
          'X-API-Key': 'your-api-key',
        },
      },
    ],
  },
}

Output Options

输出选项

ts
output: {
  target: './src/api/endpoints.ts',     // Output path (required)
  client: 'react-query',               // Client type (see table above)
  httpClient: 'fetch',                  // 'fetch' (default) | 'axios' | 'angular'
  mode: 'tags-split',                   // 'single' | 'split' | 'tags' | 'tags-split'
  schemas: './src/api/model',           // Output path for model types
  operationSchemas: './src/api/params', // Separate path for operation-derived types
  workspace: 'src/',                    // Base folder for all files
  fileExtension: '.ts',                 // Custom file extension
  namingConvention: 'camelCase',        // File naming: camelCase | PascalCase | snake_case | kebab-case
  indexFiles: true,                     // Generate index.ts barrel files
  clean: true,                          // Clean output before generating
  prettier: true,                       // Format with Prettier
  biome: true,                          // Format with Biome
  headers: true,                        // Generate header parameters
  baseUrl: '/api/v2',                   // API base URL
  // or from spec:
  // baseUrl: { getBaseUrlFromSpecification: true, index: 0, variables: { environment: 'api.dev' } },
  mock: true,                           // Generate MSW handlers (boolean or config object)
  docs: true,                           // Generate TypeDoc documentation
  // docs: { configPath: './typedoc.config.mjs' },
  allParamsOptional: true,              // Make all params optional (except path params)
  urlEncodeParameters: true,            // URL-encode path/query parameters
  optionsParamRequired: false,          // Make options parameter required
  propertySortOrder: 'Specification',   // 'Alphabetical' | 'Specification'
  tsconfig: './tsconfig.json',          // Custom tsconfig path
  override: { ... },                    // Advanced overrides (see below)
}
ts
output: {
  target: './src/api/endpoints.ts',     // 输出路径(必填)
  client: 'react-query',               // 客户端类型(见上方表格)
  httpClient: 'fetch',                  // 'fetch' (默认) | 'axios' | 'angular'
  mode: 'tags-split',                   // 'single' | 'split' | 'tags' | 'tags-split'
  schemas: './src/api/model',           // 模型类型的输出路径
  operationSchemas: './src/api/params', // 操作衍生类型的独立输出路径
  workspace: 'src/',                    // 所有文件的基础文件夹
  fileExtension: '.ts',                 // 自定义文件扩展名
  namingConvention: 'camelCase',        // 文件命名:camelCase | PascalCase | snake_case | kebab-case
  indexFiles: true,                     // 生成 index.ts 桶文件
  clean: true,                          // 生成前清理输出目录
  prettier: true,                       // 使用 Prettier 格式化
  biome: true,                          // 使用 Biome 格式化
  headers: true,                        // 生成请求头参数
  baseUrl: '/api/v2',                   // API 基础 URL
  // 或从规范中获取:
  // baseUrl: { getBaseUrlFromSpecification: true, index: 0, variables: { environment: 'api.dev' } },
  mock: true,                           // 生成 MSW 处理器(布尔值或配置对象)
  docs: true,                           // 生成 TypeDoc 文档
  // docs: { configPath: './typedoc.config.mjs' },
  allParamsOptional: true,              // 所有参数设为可选(路径参数除外)
  urlEncodeParameters: true,            // 对路径/查询参数进行 URL 编码
  optionsParamRequired: false,          // 设为必填的选项参数
  propertySortOrder: 'Specification',   // 'Alphabetical' | 'Specification'
  tsconfig: './tsconfig.json',          // 自定义 tsconfig 路径
  override: { ... },                    // 高级覆盖配置(见下文)
}

Multiple API Specs

多 API 规范配置

ts
export default defineConfig({
  petstoreV1: {
    input: { target: './specs/v1.yaml' },
    output: { target: 'src/api/v1', client: 'react-query' },
  },
  petstoreV2: {
    input: { target: './specs/v2.yaml' },
    output: { target: 'src/api/v2', client: 'react-query' },
  },
});
ts
export default defineConfig({
  petstoreV1: {
    input: { target: './specs/v1.yaml' },
    output: { target: 'src/api/v1', client: 'react-query' },
  },
  petstoreV2: {
    input: { target: './specs/v2.yaml' },
    output: { target: 'src/api/v2', client: 'react-query' },
  },
});

Filter Endpoints

过滤端点

ts
input: {
  target: './spec.yaml',
  filters: {
    mode: 'include',
    tags: ['pets'],
  },
}
ts
input: {
  target: './spec.yaml',
  filters: {
    mode: 'include',
    tags: ['pets'],
  },
}

Detailed Guides

详细指南

When the user's question involves a specific topic below, read the corresponding file from this skill's directory.
TopicFileLoad when user asks about...
TanStack Query / SWRtanstack-query.mdReact Query, Vue Query, Svelte Query, Solid Query, SWR, query hooks, invalidation, infinite queries, suspense, prefetch
Angularangular.mdAngular Query, Angular HttpClient, signals, inject functions, Angular services, providedIn
SolidStartsolid-start.mdSolidStart, @solidjs/router, query(), action(), createAsync, revalidate
Custom HTTP / Authcustom-http-clients.mdCustom mutator, authentication, tokens, interceptors, custom fetch/axios, baseURL, hook-based mutator
Zod Validationzod-validation.mdZod schemas, validation, runtime validation, coerce, strict, preprocess
Mocking / MSWmocking-msw.mdMSW mocks, testing, test setup, faker, Vitest, mock handlers, useExamples
Hono Serverhono.mdHono handlers, zValidator, composite routes, context types, server-side generation
Advanced Configadvanced-config.mdType generation, enums, per-operation overrides, FormData, JSDoc, params serializer, full example
Tooling / Workflowtooling-workflow.mdProgrammatic API, transformers, hooks, NDJSON streaming, MCP, afterAllFilesWrite
当用户的问题涉及以下特定主题时,请从本技能的目录中读取对应文件。
主题文件当用户询问以下内容时加载...
TanStack Query / SWRtanstack-query.mdReact Query、Vue Query、Svelte Query、Solid Query、SWR、查询钩子、失效、无限查询、Suspense、预获取
Angularangular.mdAngular Query、Angular HttpClient、信号、注入函数、Angular 服务、providedIn
SolidStartsolid-start.mdSolidStart、@solidjs/router、query()、action()、createAsync、重新验证
自定义 HTTP / 认证custom-http-clients.md自定义变更器、认证、令牌、拦截器、自定义 fetch/axios、baseURL、基于钩子的变更器
Zod 验证zod-validation.mdZod 模式、验证、运行时验证、强制转换、严格模式、预处理
模拟 / MSWmocking-msw.mdMSW 模拟、测试、测试配置、faker、Vitest、模拟处理器、useExamples
Hono 服务器hono.mdHono 处理器、zValidator、复合路由、上下文类型、服务端生成
高级配置advanced-config.md类型生成、枚举、按操作覆盖、FormData、JSDoc、参数序列化、完整示例
工具链 / 工作流tooling-workflow.md程序化 API、转换器、钩子、NDJSON 流、MCP、afterAllFilesWrite

OpenAPI Specification Best Practices

OpenAPI 规范最佳实践

  1. Use unique
    operationId
    for every operation — Orval uses these for function and hook names
  2. Define reusable schemas in
    components/schemas
    — reduces duplication in generated types
  3. Use tags to group operations — works with
    tags
    and
    tags-split
    modes
  4. Define response types for all operations — enables full type safety
  5. Mark required fields — affects optional/required in generated TypeScript interfaces
  6. Use
    x-enumNames
    for numeric enums — generates readable const names
  7. Provide
    example
    values
    — used by mock generation when
    useExamples: true
  8. Use
    application/x-ndjson
    content type for streaming endpoints — enables typed NDJSON generation
  1. 为每个操作使用唯一的
    operationId
    — Orval 使用该 ID 生成函数和钩子名称
  2. components/schemas
    中定义可复用模式
    — 减少生成类型中的重复代码
  3. 使用标签对操作进行分组 — 与
    tags
    tags-split
    模式兼容
  4. 为所有操作定义响应类型 — 实现完整的类型安全
  5. 标记必填字段 — 影响生成的 TypeScript 接口中的可选/必填属性
  6. 对数值枚举使用
    x-enumNames
    — 生成可读性强的常量名称
  7. 提供
    example
    — 当
    useExamples: true
    时,模拟生成会使用这些值
  8. 对流式端点使用
    application/x-ndjson
    内容类型
    — 启用类型化 NDJSON 生成

CLI Reference

CLI 参考

bash
orval                                    # Generate using auto-discovered config
orval --config ./api/orval.config.ts     # Specify config file
orval --project petstore                 # Run specific project(s)
orval --watch                            # Watch mode
orval --watch ./src                      # Watch specific directory
orval --clean                            # Clean generated files
orval --prettier                         # Format with Prettier
orval --biome                            # Format with Biome
orval --tsconfig ./src/tsconfig.json     # Custom tsconfig path
orval --mode split                       # Override output mode
orval --client react-query               # Override client
orval --mock                             # Override mock generation
orval --input ./spec.yaml --output ./api.ts  # Direct generation
bash
orval                                    # 使用自动发现的配置生成代码
orval --config ./api/orval.config.ts     # 指定配置文件
orval --project petstore                 # 运行特定项目(可多个)
orval --watch                            # 监听模式
orval --watch ./src                      # 监听指定目录
orval --clean                            # 清理生成的文件
orval --prettier                         # 使用 Prettier 格式化
orval --biome                            # 使用 Biome 格式化
orval --tsconfig ./src/tsconfig.json     # 自定义 tsconfig 路径
orval --mode split                       # 覆盖输出模式
orval --client react-query               # 覆盖客户端类型
orval --mock                             # 覆盖模拟生成配置
orval --input ./spec.yaml --output ./api.ts  # 直接生成(无需配置文件)

Resources

资源