OpenAPI 3.0 中文文档介绍 - 使用指南

209 阅读9分钟

OpenAPI规范(原Swagger规范)是一个用于描述RESTful API的规范标准。它允许开发者以标准化的方式定义API接口,使得人类和计算机都能理解API的功能,而无需访问源代码或额外文档。

OpenAPI 3.0是该规范的第三个主要版本,相比2.0版本有了显著的改进和扩展,为API设计和文档提供了更强大的表达能力。

文档地址:openapi.apifox.cn/

imgOpenAPI 3.0 规范

OpenAPI 对象

**OpenAPI**文档是由一个个对象组成的,这些对象包括了:

  • OpenAPI Object:整个 OpenAPI 文档对象
  • Info Object:描述文档信息的对象
  • Servers Object:描述服务端的对象
  • Components Object:描述组件的对象
  • Paths Object:描述接口路径的对象
  • Tag Object:接口分组对象
  • ExternalDocs Object:拓展文档对象
  • Security Object:安全性对象

通过这些对象的组成,并且生成一个 JSON 或者 YAML 文件,这就是 OpenAPI 文档。

必不可少的 OpenAPI 对象

一个最基本、最原始的 OpenAPI 对象长这样,这其中包含了三个 OpenAPI 必不可少的对象:

  • OpenAPI Object
  • Info Object
  • Paths Object
openapi: "3.0.2"
info:
  title: openAPI Demo
  version: '1.0'
paths: {}

这三个对象构成了OpenAPI文档的骨架,其中:

  • openapi字段指定了使用的OpenAPI规范版本
  • info对象提供了API的基本信息
  • paths对象定义了API的各个端点和操作

Info Object

Info Object包含API的元数据,帮助使用者了解API的基本信息:

  • title: 标题
  • description: API 描述
  • version:版本号
  • license:许可证信息
  • contact:联系人信息
  • terms of service:服务条款
openapi: "3.0.2"
info:
  title: openAPI Demo
  description: "This is an API program for teaching"
  version: '1.1'
  termsOfService: "https://openweathermap.org/terms"
  contact:
    name: "api developer"
    url: "http://myblog.cn"
    email: "youemai@gmail.com"
  license:
    name: "Apache 2.0"
    url: "http://springdoc.org"
paths: {}

可以看到文档中的效果。

imgSwagger 效果

Servers Object

Servers对象定义了API服务器的基本URL,可以指定多个服务器,如开发环境、测试环境和生产环境:

servers:
  - url: https://development.example.com/v1
    description: 开发环境
  - url: https://staging.example.com/v1
    description: 测试环境
  - url: https://api.example.com/v1
    description: 生产环境

服务器URL可以包含变量,使其更加灵活:

servers:
  - url: https://{environment}.example.com/v{version}
    description: API服务器
    variables:
      environment:
        default: api
        enum:
          - api
          - api.dev
          - api.staging
        description: API环境
      version:
        default: '1'
        enum:
          - '1'
          - '2'
        description: API版本

Paths Object

Paths Object是OpenAPI文档的核心,定义了API的各个端点和操作:

  • tags:用于对 endpoint 进行分组的组名
  • summary:操作对象的摘要信息,最好限制在 5-10 字以内,主要作为概览展示
  • description:操作对象的描述信息,尽可能的详细,展示细节信息
  • operationId:操作对象的唯一 ID
  • parameters:该端点的请求参数对象,描述如下,( requestBody 描述不在此列包含系列属)
  • name:参数名称
  • in:参数出现的位置,通常是 header,path,query,cookie
  • description:参数的描述(支持 markdown)
  • required:必填项
  • deprecated:是否弃用
  • allowEmptyValue:允许提交空值
  • style:参数序列化方式
  • explode:与数组相关的参数
  • schema:参数的模型
  • example:媒体类型的示例
  • requestBody:请求主体的描述,还可以包含一个指向 components 的 $ref 指针
  • response:响应主体的描述,通常使用标准的 HTTP 状态码,可以包含指向 components 的 $ref 指针
  • callbacks:回调对象和回调信息的描述,较为少见,不过多介绍
  • deprecated:标识该 path 是否被弃用
  • security:仅用于覆盖全局的安全授权方法
  • servers:仅用于覆盖全局的服务器访问对象
paths:
  /weather:
    get:
      tags:
      summary:
      description:
      operationId:
      externalDocs:
      parameters:
      responses:

HTTP方法

在Paths Object中,可以为每个路径定义不同的HTTP方法操作:

paths:
  /users:
    get:
      summary: 获取用户列表
      # ...其他字段
    post:
      summary: 创建新用户
      # ...其他字段
  /users/{userId}:
    get:
      summary: 获取特定用户
      # ...其他字段
    put:
      summary: 更新用户信息
      # ...其他字段
    delete:
      summary: 删除用户
      # ...其他字段

OpenAPI支持的HTTP方法包括:get、post、put、delete、options、head、patch、trace。

Parameters Object

Parameters Object定义了API操作的参数:

paths:
  /weather:
    get:
      tags:
      - Current Weather Data
      summary: "Call current weather data for one location."
      description: "^_^"
      operationId: CurrentWeatherData
      parameters:
      - name: q
        in: query
        description: "^_^"
        schema:
          type: string

参数可以出现在不同位置:

  • path:路径参数,如/users/{userId}中的userId
  • query:查询参数,如/users?role=admin中的role
  • header:HTTP头参数
  • cookie:Cookie参数

RequestBody Object

RequestBody Object定义了API操作的请求体:

requestBody:
  description: 用户信息
  required: true
  content:
    application/json:
      schema:
        type: object
        properties:
          username:
            type: string
          email:
            type: string
            format: email
          password:
            type: string
            format: password
      example:
        username: johndoe
        email: john@example.com
        password: secret123

Responses Object

Responses Object定义了API操作的响应:

responses:
  200:
    description: Successful response
    content:
      application/json:
        schema:
          title: Sample
          type: object
          properties:
            placeholder:
              type: string
              description: Placeholder description

  404:
    description: Not found response
    content:
      text/plain:
        schema:
          title: Weather not found
          type: string
          example: Not found

可以看到文档中的效果:

img文档效果

Components Object

Components Object用于存储可重用的组件,如模式、参数、响应等:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        username:
          type: string
        email:
          type: string
          format: email
  parameters:
    skipParam:
      name: skip
      in: query
      description: 跳过的记录数
      schema:
        type: integer
        format: int32
  responses:
    NotFound:
      description: 资源未找到
      content:
        application/json:
          schema:
            type: object
            properties:
              message:
                type: string

通过引用Components Object中的组件,可以避免重复定义相同的内容:

paths:
  /users:
    get:
      parameters:
        - $ref: '#/components/parameters/skipParam'
      responses:
        404:
          $ref: '#/components/responses/NotFound'

Security Object

OpenAPI 支持的四种授权的方式:

  • API key
  • HTTP
  • OAuth 2.0
  • Open ID Connect

如果使用 API key 的话,需要用到 app_id 这个字段,Security Object包含以下几个字段:

  • type:授权协议,包含了 apiKey、http、oauth2、openIdConnect
  • description:描述授权方式
  • name:秘钥名称
  • in:秘钥的位置,包含 query、header、cookie
components:
  ...
  securitySchemes:
    app_id:
      type: apiKey
      description: API key to authorize requests.
      name: appid
      in: query

可以在文档中看到此效果:

img文档效果

OAuth 2.0认证

对于更复杂的认证需求,可以使用OAuth 2.0:

components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: https://example.com/oauth/authorize
          scopes:
            read:users: 读取用户信息
            write:users: 修改用户信息
        password:
          tokenUrl: https://example.com/oauth/token
          scopes:
            read:users: 读取用户信息
            write:users: 修改用户信息
        clientCredentials:
          tokenUrl: https://example.com/oauth/token
          scopes:
            read:users: 读取用户信息
            write:users: 修改用户信息
        authorizationCode:
          authorizationUrl: https://example.com/oauth/authorize
          tokenUrl: https://example.com/oauth/token
          scopes:
            read:users: 读取用户信息
            write:users: 修改用户信息

Tags Object

主要是用来进行接口分组的对象:

paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
tags:
  - name: pets
    description: "Chimelong Animal Happy World"

我们可以看到以下的效果:

img

ExternalDocs Object

此对象不太常用,主要用来做外部文档的引用。

externalDocs:
  description: externalDocs API Documentation
  url: https://openweathermap.org/api

imgExternalDocs Object

OpenAPI的高级特性

数据模型与Schema

OpenAPI使用JSON Schema来定义数据模型,支持各种数据类型和验证规则:

components:
  schemas:
    Product:
      type: object
      required:
        - id
        - name
        - price
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
          minLength: 1
          maxLength: 100
        description:
          type: string
          nullable: true
        price:
          type: number
          format: float
          minimum: 0
        category:
          type: string
          enum: [electronics, books, clothing]
        tags:
          type: array
          items:
            type: string
        metadata:
          type: object
          additionalProperties: true

继承与组合

OpenAPI支持模式的继承和组合,使数据模型更加灵活:

components:
  schemas:
    Pet:
      type: object
      required:
        - name
        - photoUrls
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        photoUrls:
          type: array
          items:
            type: string
        status:
          type: string
          enum: [available, pending, sold]
    
    Cat:
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            huntingSkill:
              type: string
              enum: [clueless, lazy, adventurous, aggressive]
    
    Dog:
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            packSize:
              type: integer
              format: int32

多媒体类型支持

OpenAPI支持多种媒体类型,包括JSON、XML、表单数据等:

requestBody:
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/User'
    application/xml:
      schema:
        $ref: '#/components/schemas/User'
    application/x-www-form-urlencoded:
      schema:
        $ref: '#/components/schemas/UserForm'
    multipart/form-data:
      schema:
        $ref: '#/components/schemas/UserFormWithFile'

使用 Apifox 管理 OpenAPI API

Apifox 是一款集 API文档、API管理、API测试于一身的超级多功能 API 工具,日常用 Apifox 来管理 OpenAPI 的 API 项目,那是再合适不过了。

Apifox 的 API 管理

Apifox 的 API 管理功能很齐全,包括:

  • 接口数管理
  • operationID
  • Mock 功能
  • 请求定义、请求示例
  • 响应定义、响应示例
  • 唯一标识

立即体验 Apifox

OpenAPI 3.0 中文文档

Apifox 的自动化测试

Apifox 的自动化测试也很完善,功能包括:

  • 测试用例:可以测试多个接口或接口用例
  • 测试套件:可以测试多个测试用例
  • 可以设置循环数、延迟书、环境、线程数等参数进行运行
  • 支持导出测试报告
  • 支持查看单个接口的测试结果
  • 支持查看测试结果的详细参数

OpenAPI 3.0 中文文档

OpenAPI 3.0 中文文档

Mock 功能

Apifox 支持 Mock 功能,定义完接口响应之后,通过本地 Mock 功能可得到 Mock 数据。

点击 发送,即可获取 Mock 数据。

OpenAPI 3.0 中文文档

导出导入 OpenAPI

Apifox 支持导出导入 OpenAPI,如果你想要进行 API 项目迁移的时候,可以考虑下这个功能,能让你以最低的成本,去进行项目迁移。

OpenAPI 3.0 中文文档

团队协作功能

Apifox提供了强大的团队协作功能,包括:

  • 项目共享:团队成员可以共同访问和编辑API项目
  • 权限管理:可以为不同角色设置不同的权限
  • 版本控制:记录API的变更历史
  • 评论功能:团队成员可以对API进行讨论和反馈
  • 通知系统:API变更时自动通知相关人员

环境变量与全局变量

Apifox支持环境变量和全局变量,使API测试更加灵活:

  • 环境变量:可以为不同环境(开发、测试、生产)设置不同的变量值
  • 全局变量:在整个项目中共享的变量
  • 动态变量:可以通过脚本动态生成的变量

OpenAPI的最佳实践

API设计原则

使用OpenAPI设计API时,应遵循以下原则:

  1. 一致性:保持API的命名、参数、响应格式的一致性
  2. 简单性:API应该简单易用,避免不必要的复杂性
  3. 可扩展性:设计API时考虑未来的扩展需求
  4. 版本控制:使用版本控制管理API的变更
  5. 安全性:考虑API的安全需求,如认证、授权、数据加密等

文档编写技巧

编写高质量的OpenAPI文档,应注意以下几点:

  1. 详细的描述:为API提供详细的描述,包括用途、使用场景等
  2. 准确的示例:提供准确的请求和响应示例
  3. 清晰的错误信息:定义清晰的错误码和错误信息
  4. 分组和标签:使用标签对API进行分组,提高文档的可读性
  5. 保持更新:随着API的变更,及时更新文档

关于 Apifox

  • 集成了 API 文档、API 调试、API Mock、API 自动化测试 API 一体化协作平台
  • 拥有更先进的 API 设计/开发/测试工具
  • Apifox = Postman + Swagger + Mock + JMeter

欢迎体验一下:在线使用 Apifox

总结

OpenAPI 3.0规范为API设计和文档提供了强大的工具,通过标准化的方式描述API,使得API的开发、测试和使用变得更加高效。而Apifox作为一款集成了API文档、管理、测试功能的工具,进一步简化了API的开发流程,提高了开发效率。

希望本文能帮助你更好地理解OpenAPI 3.0规范,并在实际项目中充分利用它的优势。如果你有任何问题或建议,欢迎在评论区留言交流!