Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define enum of keys in a map, Swagger

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.

like image 625
Fundhor Avatar asked May 17 '16 10:05

Fundhor


People also ask

Can I use an enum for map?

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

How does swagger define key value pairs?

A dictionary (also known as a map, hashmap or associative array) is a set of key/value pairs. OpenAPI lets you define dictionaries where the keys are strings. To define a dictionary, use type: object and use the additionalProperties keyword to specify the type of values in key/value pairs.

Where do you define enums?

The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.


1 Answers

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'
like image 91
Arnaud Lauret Avatar answered Sep 16 '22 13:09

Arnaud Lauret