如何在与 AWS API 网关兼容的 OpenAPI 3.0.x 中声明可空 属性

How to declare nullable property in OpenAPI 3.0.x that's compatible with AWS API Gateway

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

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

有什么方法可以在 OpenAPI 3.0.x 中声明 nullable 属性 以便 AWS API 网关识别和配置底层模型也是这个设置?

示例打开API 规范

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

生成的模型的结果 JSON 架构文档

{
  "required" : [ "date" ],
  "type" : "object",
  "properties" : {
    "date" : {
      "type" : "string",
      "format" : "date-time"
    }
  }
}

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

有什么帮助吗?

AWS API Gateway 需要 JSON 架构格式的模型,而不是 OpenAPI 架构格式。这是相关注释 from the documentation(强调我的):

API Gateway supports most of the OpenAPI 2.0 specification and the OpenAPI 3.0 specification, with the following exceptions:

  • ...
  • API Gateway models are defined using JSON schema draft 4, instead of the JSON schema used by OpenAPI.

这意味着 AWS API 网关期望 type: [string, 'null'] 而不是 type: string + nullable: true

然而,type: [string, 'null'] in OpenAPI 3.0 (it's valid in OAS 3.1 though). What you can do is pre-process your existing OpenAPI file before importing it to AWS API Gateway and change the nullable type definitions to the format/syntax that AWS expects. You can try using tools such as openapi-schema-to-json-schema.