Search code examples
jsonyamlswaggeropenapicode-generation

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?


Solution

  • 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'