13

I need to define a map. But I also want to limit the possible keys.

Here is what I tried to do.

type: object
    description: Key Value Map with user data. Possible values for the keys ("KEY_1", "KEY_2", "KEY_3")
    additionalProperties:
      type: object

Is it possible to use an enumeration to define the keys ? (the map returns int String, Object. But this is not part of the problem)

Thank you for your help.

Fundhor
  • 3,369
  • 1
  • 25
  • 47
  • Related: [How to write OpenAPI 3 (Swagger) specification for property name in `map` object?](https://stackoverflow.com/q/46552863/113116) – Helen Apr 28 '20 at 18:46

2 Answers2

5

When you use additionalPropertie you cannot define the set of accepted keys. But if my understanding is correct, two example of this hashmap as JSON could be:

JSON example 1:

{
  "KEY_1": { ... },
  "KEY_2": { ... },
  "KEY_3": { ... }
}

JSON example 2:

{
  "KEY_1": { ... },
  "KEY_3": { ... }
}

This hashmap with a defined set of key is basically an object which contains optional (i.e. non required) properties of type object and therefore could be defined just like any other object:

type: object
properties:
  KEY_1:
    type: object
  KEY_2:
    type: object
  KEY_3:
    type: object

nb: it would be a good idea to use a $ref to avoid having to define the object for each KEY property:

type: object
properties:
  KEY_1:
    $ref: '#/definitions/TheObjectDefinition'
  KEY_2:
    $ref: '#/definitions/TheObjectDefinition'
  KEY_3:
    $ref: '#/definitions/TheObjectDefinition'
Arnaud Lauret
  • 4,961
  • 1
  • 22
  • 28
0

You can simulate a dictionary/map using a list.

First you define an entry object, where you can restrict types.

Then you define a map as an array of entries.

Entry:
  type: object
  properties:
    key:
      $ref: '#/components/schemas/SomeEnum'
    value:
      type: string
SimulatedMap:
  type: object
  properties:
    entries:
      type: array
      items:
        $ref: '#/components/schemas/Entry'
Łukasz Chorąży
  • 506
  • 1
  • 6
  • 23