为什么 OpenAPI 中有不同的组件类型?

Tho*_*mas 4 swagger openapi

尝试了解 OpenAPI 在components/schemas部分 中定义可重用对象或在components/requestBodies它确实是作为请求正文的对象时定义可重用对象之间的区别。

除了分离不是真正域对象的简单请求有效负载之外,还有什么区别吗?为什么我们有不同的schemasrequestBodies和部分responses

特别是在查看生成的客户端代码时,我发现在 中定义的类schemasrequestBodies.

Hel*_*len 7

模式描述了 API 使用的特定数据结构例如某个对象、它的属性、它们的数据类型等等。

其他一些组件类型使用架构作为其构建块之一。

请求主体组件定义请求主体是必需的还是可选的、请求主体支持的媒体类型(例如,、application/json)以及每种媒体类型的模式(这些模式可以相同或不同)。multipart/form-dataapplication/octet-stream

类似地,响应组件不仅定义响应模式,还定义可能的响应媒体类型和响应标头。

OpenAPI 组件类型

如果我们将指示的部分重写为components,我们最终会得到:

paths:
  /users:
    post:
      summary: Create a user
      requestBody:
        $ref: '#/components/requestBodies/createUser'
      responses:
        '201':
          $ref: '#/components/responses/userCreated'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          format: uuid
          readOnly: true
        name:
          type: string
          example: Helen
  
  requestBodies:
    createUser:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/User'
        application/x-www-form-urlencoded:
          schema:
            $ref: '#/components/schemas/User'
  
  responses:
    userCreated:
      description: >-
        The user was successfully created.
        The response contains the created user.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/User'
Run Code Online (Sandbox Code Playgroud)

虽然使用components/schemas为模式命名是一种常见的做法,但使用components/requestBodiescomponents/responses代替内联定义更方便。components仅当相同的请求正文定义或响应定义在多个位置重复时,您通常才会将后者放入其中。例如,401 和 403 响应通常在所有操作中具有相同的架构和描述,因此您可能希望$ref它们减少重复,而需要唯一描述的 200/201 响应可以保持内联。


特别是在查看生成的客户端代码时,我发现在 中定义的类schemasrequestBodies.

这可能因代码生成而异。但这可能是因为模式被转换为,而请求主体和响应属性(例如媒体类型)是用注释来表达的。因此,在代码生成上下文中,请求主体和响应是内联定义还是在components.