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

前端 未结 3 1400
醉酒成梦
醉酒成梦 2021-01-07 16:50

When using JSON Schema and Open API specification (OAS) to document a REST API, how do I define the UUID property?

3条回答
  •  梦谈多话
    2021-01-07 17:25

    Since the question was originally asked the JSON Schema spec has been extended to provide built-in support for specifying and validating that a JSON field of type string is a UUID - specifically that it adheres to the format of a UUID as defined by RFC4122, e.g. “f81d4fae-7dec-11d0-a765-00a0c91e6bf6”.

    The support was added in JSON Schema spec version 2019-09 (previously known as draft-08). The JSON Schema Validation component spec was extended such that the existing ‘format' keyword that can be specified for schema fields of type string now supports a new built-in format named "uuid".

    The example JSON schema below declares a (mandatory) field named "id" of type string that must be formatted as 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"]
    }
    

    Note that at the time of writing, the section of the JSON Schema user guide ("Understanding JSON Schema") covering examples of built-in string validation - JSON Schema Reference > Type-specific keywords > string > Format - doesn’t mention UUID supports, as it’s out of date - it currently only describes JSON Schema draft-7.

    For the Java developers among you, the RFC4122 format used by JSON schema is compatible with the string representation of Java’s UUID class - it’s Javadoc also mentions RFC 4122.

    For more details see -

    • The JSON Schema Validator spec section 7. A Vocabulary for Semantic Content With “format” > 7.3. Defined Formats > 7.3.5. Resource Identifiers - The official spec.
    • This GitHub issue https://github.com/json-schema-org/json-schema-spec/issues/542 (01/2018) requested that support be added. And the enhancement was duly implemented in 03/2019. See pull request https://github.com/json-schema-org/json-schema-spec/pull/715.

提交回复
热议问题