如何在 JSON 架构中定义 UUID 属性 并打开 API (OAS)

How to define UUID property in JSON Schema and Open API (OAS)

当使用JSON Schema and Open API specification (OAS) to document a REST API, how do I define the UUID时属性?

到目前为止我发现的唯一方法是手动将 RegEx 模式指定为可重用架构组件:

openapi: 3.0.1

paths:
  /transactions/:
    post:
      responses:
        200:
          content:
            application/json:
              schema:
                type: object
                properties:
                  transactionId:
                    $ref: '#/components/schemas/uuid'

components:
  schemas:
    uuid:
      type: string
      pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
      # the regex above limits the length;
      # however, some tools might require explicit settings:
      minLength: 36
      maxLength: 36

但是,我肯定想使用更标准化的方法。

UUID 没有内置 type,但 OpenAPI 规范建议使用

type: string
format: uuid

来自 Data Types 部分(强调我的):

Primitives have an optional modifier property: format. OAS uses several known formats to define in fine detail the data type being used. However, to support documentation needs, the format property is an open string-valued property, and can have any value. Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification.

例如,Swagger Codegen 将 format: uuid 映射到 C# 中的 System.Guid 或 Java 中的 java.util.UUID。不支持 format: uuid 的工具会将其处理为 type: string.

自最初提出问题以来,JSON 架构规范已扩展为提供内置支持,用于指定和验证字符串类型的 JSON 字段是否为 UUID - 特别是它遵循 RFC4122 定义的 UUID 格式,例如“f81d4fae-7dec-11d0-a765-00a0c91e6bf6”。

在 JSON 架构规范版本 2019-09(以前称为 draft-08)中添加了支持。 JSON 架构验证组件规范得到了扩展,因此可以为字符串类型的架构字段指定的现有“格式”关键字现在支持名为“uuid”的新内置格式。

下面的示例 JSON 架构声明了一个名为“id”的字符串类型的(强制)字段,该字段必须格式化为 UUID -

{
  "$schema": "http://json-schema.org/draft/2019-09/schema#",
  "title": "My JSON object schema",
  "description": "Schema for the JSON representation of my JSON object.",

  "type": "object",
  "properties": {
    "id": {
      "description": "The unique identifier for my object. (A UUID specified by RFC4122).",
      "type": "string",
      "format": "uuid"
    }
  },
  "required": ["id"]
}

请注意,在撰写本文时,JSON 架构用户指南的部分("Understanding JSON Schema") covering examples of built-in string validation - JSON Schema Reference > Type-specific keywords > string > Format - 未提及 UUID 支持,因为它已过时 - 目前仅描述 JSON 架构草案 7.

对于你们中的 Java 开发人员,JSON 架构 使用的 RFC4122 格式 与 Java 的字符串表示兼容' s UUID class - Javadoc 也提到了 RFC 4122.

有关详细信息,请参阅 -