首页 > 解决方案 > OpenAPI - 对同一资源的每次操作不同的架构

问题描述

我正在使用 OpenAPI 3.0 来描述一个 API,其中每个资源都有一个基于其操作的微妙不同的架构。本质上,某些属性是可编辑的和/或需要的,具体取决于它是 POST 还是 PUT 请求。

除了为这样的每个操作指定架构之外,还有更好的方法吗?(其中 field2 在 PUT 上是只读的)

理想情况下,我想在一个地方指定架构(即所有属性),然后在每个操作上覆盖一些属性(例如 readOnly)。

{
   "paths":{
      "/users":{
         "put":{
            "responses":{
               "200":{
                  "$ref":"#/components/schemas/users_put"
               }
            }
         },
         "post":{
            "responses":{
               "200":{
                  "$ref":"#/components/schemas/users_post"
               }
            }
         }
      }
   },
   "components":{
      "schemas":{
         "users_post":{
            "properties":{
               "field1":{
                  "readOnly":true,
                  "type":"integer"
               },
               "field2":{
                  "type":"string"
               }
            }
         },
         "users_put":{
            "properties":{
               "field1":{
                  "readOnly":true,
                  "type":"integer"
               },
               "field2":{
                  "type":"string",
                  "readOnly":true
               }
            }
         }
      }
   }
}

标签: openapi

解决方案


据我所知,openapi/swagger 模型中没有覆盖机制。但是组合(扩展)模型是可用的

由于在您的示例中,您只需要更新readOnly指令(这意味着您标记仅在响应中可用的属性)当您分别描述请求和响应时尝试其他方法。

例如在您的示例中, put 和 post 方法的响应将是相同的(因为它们都有field1and field2),并且只有 put 会有请求(因为在 post 中所有字段都是只读的):

为了简洁起见,我使用 yaml,但很容易转换为 json 回来

paths:
  "/users":
    put:
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/users_put_request'
      responses:
        '200':
          "$ref": "#/components/schemas/users_response"
    post:
      responses:
        '200':
          "$ref": "#/components/schemas/users_response"
components:
  schemas:
    users_response:
      field1:
        type: integer
      field2:
        type: integer

    users_put_request:
      field2:
          type: string

可能使用这种方法可以明确地描述模型的不同部分。


推荐阅读