当使用JSON Schema和Open API specification (OAS)来记录REST API时,如何定义UUID属性?
当使用JSON Schema和Open API specification (OAS)来记录REST API时,如何定义UUID属性?
没有针对UUID的内置type
,但是OpenAPI规范建议使用
type: string
format: uuid
以下内容来自于 数据类型 部分(我加粗了):
原始类型具有可选的修饰符属性:
format
。OAS使用几种已知格式来详细定义所使用的数据类型。然而,为了支持文档需求,format
属性是一个开放的字符串值属性,可以具有任何值。即使未被此规范定义,也可以使用例如"email"
、"uuid"
等格式。
例如,Swagger Codegen将format: uuid
映射到C#中的System.Guid
或Java中的java.util.UUID
。不支持format: uuid
的工具将其处理为type:string
。
format
仅为注释,但如果您使用“格式断言词汇”的方式定义 JSON Schema 方言,则可以使用 format
的断言版本。 - Relequestual到目前为止,我找到的唯一方法是手动将正则表达式模式指定为可重用的模式组件:
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
但是,我肯定会想要采用更标准化的方法。
pattern: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
- Ktiprpattern: '^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$'
和 minlength: 32
。 - Papooch{
"$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 Schema用户指南("理解JSON Schema")中涵盖内置字符串验证示例 - JSON Schema参考>类型特定关键字>字符串>格式 - 没有提到UUID支持,因为它已经过时了,它目前只描述了JSON Schema draft-7。
对于Java开发人员,JSON模式使用的RFC4122格式与Java的UUID类的字符串表示形式兼容 - 它的Javadoc也提到了RFC 4122。
更多细节请参见-
{"id": '9151f21f-43ae-43b4-92f3-f4af67cdf544'}
可以验证...从该UUID中删除任何内容或用垃圾替换它,现在会导致验证失败。 - some bits flipped