OpenAPI 规范基础

顶层字段的结构:openapi / info / servers / paths / components,以及 $ref 复用。

Beginner
Key Points一份规范由五块组成:版本、元信息、服务器列表、路径与操作、可复用组件;跨文件复用靠 $ref。

顶层结构

YAML
openapi: 3.0.3            # 规范版本,必填
info:                     # 元信息,必填
  title: User API
  version: 1.0.0
  description: 用户服务接口
servers:                  # 服务器列表
  - url: https://api.example.com/v1
    description: 生产
  - url: http://localhost:8080/v1
    description: 本地
paths:                    # 路径与操作,必填
  /users:
    get: { ... }
    post: { ... }
components:               # 可复用组件
  schemas: { ... }
  parameters: { ... }
  responses: { ... }
  securitySchemes: { ... }

paths 与 operation

Keys under paths are path templates; values hold HTTP methods. Every operation needs responses and usually summary, parameters, requestBody, tags.

YAML
paths:
  /users/{id}:
    get:
      tags: [Users]
      summary: 查询单个用户
      operationId: getUser
      parameters:
        - $ref: '#/components/parameters/UserId'
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          $ref: '#/components/responses/NotFound'

components 与 $ref

Extract repeated structures into components and reference them with $ref. The JSON pointer #/components/schemas/User means "components.schemas.User in this file"; refs may also point at other files, e.g. ./schemas/user.yaml.

YAML
components:
  parameters:
    UserId:
      name: id
      in: path
      required: true
      schema:
        type: integer
        format: int64
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        email:
          type: string
          format: email
  responses:
    NotFound:
      description: 资源不存在
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

schema 的常用关键字

KeywordMeaningExample
typeData typestring / integer / object / array
formatSemantic hintint64 / date-time / email
enumFixed value set[pending, paid, shipped]
requiredMandatory properties[id, name]
minimum / maximumNumeric boundsminimum: 0
patternRegex constraint'^1[3-9]\d{9}$'
oneOf / anyOf / allOfCompositionSee advanced chapter
OpenAPI 3.0 schemas are a subset of JSON Schema; unsupported keywords such as patternProperties are silently ignored by some tools. Use 3.1 for full JSON Schema.

Friends & Partners