Pooja
Pooja

Reputation: 115

How to describe a map with object keys in OpenAPI/Swagger?

In my REST API, I want to use a hashmap Map<Foo, List<Bar>> where Foo and Bar are user-defined classes. How to describe such a map in OpenAPI (Swagger)?

Upvotes: 6

Views: 19624

Answers (2)

Alexey Stepanov
Alexey Stepanov

Reputation: 811

You can do this with additionalProperties
See docs

components:
  schemas:
    Messages:        # <---- map
      type: object
      additionalProperties:
        type: string

It represents in json as:

{
  "Alex":  "Hello",
  "Ann":  "Hi!"

   ^^ key is a string
}

Upvotes: 3

Helen
Helen

Reputation: 97847

OpenAPI (Swagger) only supports maps with string keys such as:

{
  "en":  "Hello",
  "fr":  "Bonjour"

   ^^ key is a string
}

It is not possible to define maps with non-string keys, such as Map<Foo, Bar>. You can submit a feature request in the OpenAPI Specification repository: https://github.com/OAI/OpenAPI-Specification/issues.

The most you can do is define your hashmap as just type: object, which means an arbitrary object.

Upvotes: 4

Related Questions