Home > Mobile >  Message examples in OpenAPI 3 YAML specification
Message examples in OpenAPI 3 YAML specification

Time:07-13

OpenAPI v3 offers using JSON or YAML format.

I prefer using YAML to create API specifications. YAML's readability is much better for me as an API designer.

However, sometimes I need to embed a message example whose type is object. I usually have the examples in JSON format. So I would do the following:

examples:
  singlePet:
    summary: Single pet
    description: A request containing a single pet
    value: |
      {
        "pets" : [
          {
            "petType" : "DOG",
            "name" : "Ben"
          }
        ]
      }

However, such value is a string, not an object, whereas OpenAPI expects an object.

Do we have any options to embed a JSON as an example value in the YAML specification?

Currently, I convert the JSON to YAML and embed the YAML:

examples:
  singlePet:
    summary: Single pet
    description: A request containing a single pet
    value:
      pets:
        - petType: DOG
          name: Ben

CodePudding user response:

YAML is a superset of JSON. This means you can use JSON syntax for objects and arrays within a YAML document.

In your first example, you can just remove the | after the value: to keep the example value as an object.

The following are equivalent:

examples:
  singlePet:
    summary: Single pet
    description: A request containing a single pet
    value:
      {
        "pets" : [
          {
            "petType" : "DOG",
            "name" : "Ben"
          }
        ]
      }
examples:
  singlePet:
    summary: Single pet
    description: A request containing a single pet
    value:
      pets:
      - petType: DOG
        name: Ben

Alternatively, you can use externalValue to point to an external file containing sample JSON.

examples:
  singlePet:
    summary: Single pet
    description: A request containing a single pet
    externalValue: 'https://api.example.com/docs/examples/pet.json'
  • Related