如何在与 AWS API Gateway 兼容的 OpenAPI 3.0.x 中声明可为 null 的属性

Mar*_*cak 6 jsonschema aws-api-gateway openapi

我们一直在使用 OpenAPI 3.0.x 规范,它添加了声明nullable属性的功能。

当我将此 OpenAPI 导入 AWS API Gateway 时,相应的模型不支持此可为空的设置。

有没有办法在 OpenAPI 3.0.x 中声明nullable属性,以便 AWS API 网关也使用此设置识别并配置底层模型?

OpenAPI 规范示例

openapi: "3.0.2"
info:
  title: Test
  description: |
    API
  version: "0.1.0"
  license:
    name: Private
    url: https://fillme.one/license
servers:
  - url: /api/v1
paths:
  /accounts:
    post:
      operationId: repa
      responses:
        200:
          description: test
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                date:
                  type: string
                  format: date-time
                  nullable: true
              required:
                - date
Run Code Online (Sandbox Code Playgroud)

生成的模型的结果 JSON 模式文档

{
  "required" : [ "date" ],
  "type" : "object",
  "properties" : {
    "date" : {
      "type" : "string",
      "format" : "date-time"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

显然,类型应该是 的并集["string", null],但 AWS API Gateway 忽略了 OpenAPI 规范。

有什么帮助吗?

Hel*_*len 8

AWS API Gateway 需要 JSON Schema 格式的模型,而不是 OpenAPI Schema 格式。这是文档中的相关注释(重点是我的):

API Gateway 支持大多数 OpenAPI 2.0 规范和 OpenAPI 3.0 规范,但以下例外:

  • ...
  • API 网关模型是使用JSON 架构草案 4定义的,而不是 OpenAPI 使用的 JSON 架构。

这意味着 AWS API Gateway 需要type: [string, 'null']而不是type: string+ nullable: true

但是,在 OpenAPI 3.0 中type: [string, 'null'] 不是有效语法(但在 OAS 3.1 中有效)。您可以做的是在将现有 OpenAPI 文件导入 AWS API Gateway 之前对其进行预处理,并将可为空的类型定义更改为 AWS 期望的格式/语法。您可以尝试使用诸如openapi-schema-to-json-schema.