简体   繁体   中英

How to have multiple infinite objects without an array - Open API / Swagger

I'm trying to setup an open api spec for the following snippet of JSON:

                    "test1": {
                        "1739573957": {
                            "tester1": 123,
                            "tester2": "Company"
                        },
                        "64903826718": {
                            "tester1": 123,
                            "tester2": "Company"
                        }
                        "5902849189": {
                            "tester1": 123,
                            "tester2": "Company"
                        }
                    }

The objects inside test1 have randomized guids and are listed in a way that typically would be an array, but is not. There could potentially be an infinite number of objects inside test 1. Anyone know how to set this up?

You are looking for the free-form-object :

A free-form object (arbitrary property/value pairs) is defined as: type: object

This is equivalent to

type: object additionalProperties: true

and

type: object additionalProperties: {}

However, if you can change the API, I'd highly recommend to change it to an array of tests or whatever the object defines. Put the id as property into this object and you're good to go. This makes creating DTOs for it a lot easier.

test1 is a string-to-object dictionary and can be defined as follows (assuming OpenAPI 3):

components:
  schemas:
    Tester:  # Or however you would name the nested objects
      tester1:
        type: integer
        example: 123
      tester2:
        type: string
        example: Company

...
test1:
  type: object
  additionalProperties:
    $ref: '#/components/schemas/Tester'

  # Optional example for the `test1` property
  example:
    '1739573957':
      tester1: 123
      tester2: Company
    '64903826718':
      tester1: 123
      tester2: Company

The objects inside test1 have randomized guids

In OpenAPI 3.1, you can use patternProperties instead of additionalProperties to define that the keys inside test1 are numeric strings. Earlier OpenAPI versions don't have a way to define the format of dictionary keys.

# openapi: 3.1.0

test1:
  type: object
  patternProperties:  # <-----
    '^\d+$':          # <-----
      $ref: '#/components/schemas/Tester'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM