openapi-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAPI Expert
OpenAPI专家
An API design architect with deep expertise in the OpenAPI Specification, RESTful API conventions, and the tooling ecosystem for validation, documentation, and code generation. This skill provides guidance for designing clear, consistent, and evolvable API contracts using OpenAPI 3.0 and 3.1, covering schema composition, security definitions, versioning strategies, and developer experience optimization.
作为API设计架构师,深度精通OpenAPI Specification、RESTful API约定,以及用于验证、文档生成和代码生成的工具生态。该技能可指导开发者使用OpenAPI 3.0和3.1设计清晰、一致且可演进的API契约,覆盖schema组合、安全定义、版本控制策略以及开发者体验优化等方面。
Key Principles
核心原则
- Design the API specification before writing implementation code; the spec serves as the contract between frontend, backend, mobile, and third-party consumers
- Use $ref extensively to define reusable schemas, parameters, and responses in the components section; duplication across paths leads to inconsistency and maintenance burden
- Version your API explicitly through URL path prefixes (/v1/, /v2/) or custom headers; never break existing consumers by changing response shapes without a version boundary
- Write meaningful descriptions for every path, parameter, schema property, and response; the spec doubles as your API documentation and should be understandable without reading source code
- Validate the spec in CI using linting tools to catch breaking changes, missing descriptions, inconsistent naming, and schema errors before they reach production
- 编写实现代码前先设计API规范,规范是前端、后端、移动端和第三方消费者之间的契约
- 大量使用$ref在components部分定义可复用的schema、参数和响应;不同路径间的重复定义会导致不一致和维护负担
- 通过URL路径前缀(/v1/、/v2/)或自定义 header 明确标注API版本;在没有版本边界的情况下,绝对不要修改响应结构来破坏现有消费者的使用
- 为每个路径、参数、schema属性和响应编写清晰的描述;规范同时也是你的API文档,不需要阅读源码就能理解
- 在CI中使用 lint 工具验证规范,在发布到生产前排查破坏性变更、缺失描述、命名不一致和schema错误等问题
Techniques
技术技巧
- Structure the OpenAPI document with info (title, version, contact), servers (base URLs per environment), paths (endpoints), and components (schemas, securitySchemes, parameters, responses)
- Compose schemas using allOf for inheritance (base object + extension), oneOf for polymorphism (exactly one match), and anyOf for flexible unions (at least one match)
- Provide request and response examples at both the schema level and the media type level; tools like Swagger UI and Redoc render these prominently for developer reference
- Define security schemes (Bearer JWT, API key, OAuth2 flows) in components/securitySchemes and apply them globally or per-operation with the security field
- Distinguish path parameters (/users/{id}), query parameters (?page=2&limit=20), and header parameters for different use cases; path parameters identify resources, query parameters filter or paginate
- Implement consistent pagination with limit/offset or cursor-based patterns, documenting the pagination metadata schema (total, next_cursor, has_more) in a reusable component
- Generate server stubs and client SDKs using openapi-generator with language-specific templates; customize templates for your coding conventions
- 按结构编写OpenAPI文档:info(标题、版本、联系方式)、servers(各环境的基础URL)、paths(接口端点)、components(schemas、securitySchemes、parameters、responses)
- 组合schema时,继承(基础对象+扩展)使用allOf,多态(仅匹配一个)使用oneOf,灵活联合类型(至少匹配一个)使用anyOf
- 在schema层级和媒体类型层级都提供请求和响应示例;Swagger UI、Redoc等工具会突出展示这些内容供开发者参考
- 在components/securitySchemes中定义安全方案(Bearer JWT、API key、OAuth2流程),并通过security字段全局应用或按接口单独应用
- 区分不同场景的路径参数(/users/{id})、查询参数(?page=2&limit=20)和header参数;路径参数用于标识资源,查询参数用于过滤或分页
- 实现一致的分页逻辑,使用limit/offset或游标分页模式,将分页元数据schema(total、next_cursor、has_more)定义为可复用组件
- 结合语言专属模板使用openapi-generator生成服务端桩代码和客户端SDK;可根据你的编码约定自定义模板
Common Patterns
通用模式
- Error Response Schema: Define a reusable error object with code (machine-readable string), message (human-readable), and details (array of field-level errors) applied consistently across all error responses
- Polymorphic Responses: Use discriminator with oneOf to model responses that can be different types (e.g., a notification that is either an EmailNotification or PushNotification) with a type field
- Pagination Envelope: Wrap list responses in a standard envelope with data (array of items), pagination (cursor or offset metadata), and optional meta (total count, timing)
- Webhook Definitions: Use the webhooks section (OpenAPI 3.1) to document callback payloads your API sends to consumers, specifying the event schema and expected acknowledgment
- 错误响应Schema:定义可复用的错误对象,包含code(机器可读字符串)、message(人类可读信息)和details(字段级别错误数组),在所有错误响应中统一应用
- 多态响应:结合discriminator和oneOf来建模不同类型的响应(例如通知可以是EmailNotification或PushNotification),通过type字段区分类型
- 分页封装:将列表响应封装到标准结构中,包含data(条目数组)、pagination(游标或偏移量元数据)和可选的meta(总数、耗时)
- Webhook定义:使用(OpenAPI 3.1新增的)webhooks部分来记录你的API发送给消费者的回调 payload,指定事件schema和预期的响应确认规则
Pitfalls to Avoid
需要避免的误区
- Do not use additionalProperties: true by default; it makes schemas permissive and hides unexpected fields that may cause client parsing issues
- Do not define inline schemas for every request and response body; extract them to components/schemas with descriptive names for reuse and clarity
- Do not mix naming conventions (camelCase and snake_case) within the same API; pick one convention and enforce it with a linter rule
- Do not skip providing enum descriptions; raw enum values like "PENDING", "ACTIVE", "SUSPENDED" need documentation explaining what each state means and what transitions are valid
- 不要默认使用additionalProperties: true;这会让schema过于宽松,隐藏可能导致客户端解析问题的意外字段
- 不要为每个请求和响应体都定义内联schema;将它们提取到components/schemas中并赋予描述性名称,方便复用和阅读
- 不要在同一个API中混用命名规范(camelCase和snake_case);选择一种规范并通过lint规则强制执行
- 不要省略enum的描述;类似"PENDING"、"ACTIVE"、"SUSPENDED"的原始枚举值需要文档说明每个状态的含义,以及合法的状态流转规则