52

I am designing an API and I want to define an enum Severity which can have values LOW, MEDIUM or HIGH. Internally Severity gets stored as an integer so I want to map these to 2,1 and 0 respectively. Is there a way to do this in an OpenAPI definition? This is currently what I have for Severity:

 severity:
   type: string
   enum:
   - HIGH
   - MEDIUM
   - LOW

2 Answers 2

100

OpenAPI 3.1

OpenAPI 3.1 uses the latest JSON Schema, and the recommended way to annotate individual enum values in JSON Schema is to use oneOf+const instead of enum. This way you can specify both custom names (title) and descriptions for enum values.

Severity:
  type: integer
  oneOf:
  - title: HIGH
    const: 2
    description: An urgent problem
  - title: MEDIUM
    const: 1
  - title: LOW
    const: 0
    description: Can wait forever

Note: This schema still uses 1, 2, 3 (i.e. the const values) as the enum values in the actual request/response payload, but code generators can use the title to assign custom names to those values in client/server code, for example:

# Python
class Severity(Enum):
    HIGH = 2
    MEDIUM = 1
    LOW = 0

OpenAPI 3.0 and 2.0

These versions do not have a way to define custom names for enum values, but some tools provide x- extensions for this purpose. For example:

Check with your tooling vendors to see if they have a similar extension.

Sign up to request clarification or add additional context in comments.

3 Comments

Any mapping Technical "Keyword" => Display "Label" available for code generation ?
@FrançoisF. I don't know. But the most popular codegens are open source, so you can customize them to your needs.
kiota also support x-ms-enum
13

Open API 3.0

You can use description:

Severity:
  type: integer
  enum: [2, 1, 0]
  description: >
    dictionary:
      * 2 HIGH
      * 1 MEDIUM
      * 0 LOW

It will not affect automatic code generation, but will be visible in generated documentation.

1 Comment

here what would be the type of request object for this contract? Here type is int then it expects int type or enum type as input?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.