Customize Enums
Default Behavior
To ensure that your SDK generated by Speakeasy is compilable, there should be no naming conflicts in your spec.
Enums can be tricky because they are often defined inline and not as a schema definition.
Here's how Speakeasy handles enums: If an enum is defined as a schema, the schema name is used to represent the enum. If an enum is defined inline, the name will be constructed from the position of the enum in the document.
Here's an example showing the default behavior for both inline and schema-based enums.
Inline Enum:
paths: /user/: post: operationId: createUser requestBody: content: application/json: schema: type: object properties: email: type: string format: email description: The user's email address status: type: string description: The user's status enum: - basic - premium country: $ref: "#/components/schemas/Country" responses: "200": description: OKcomponents: schemas: Country: type: string description: The user's country enum: - US - UK
user = { email: "test@speakeasyapi.dev", status: CreateUserRequestBodyStatusEnum.Basic country: CountryEnum.UK }
Rename Inline Enums
For enums defined inline, Speakeasy supports $anchor
keywords (opens in a new tab), which you can use to rename enums:
Inline Enum with Anchor:
paths: /user/: post: operationId: createUser requestBody: content: application/json: schema: type: object properties: email: type: string format: email description: The user's email address status: $anchor: Status type: string description: The user's role enum: - basic - premium country: $ref: "#/components/schemas/Country" responses: "200": description: OKcomponents: schemas: Country: type: string description: The user's country enum: - US - UK
user = { email: "test@speakeasyapi.dev", status: StatusEnum.Basic country: CountryEnum.UK }
Enum Member Names
By default, Speakeasy will convert the enum value to a suitable name (namespaced by the enum type name if necessary to avoid naming collisions) for the enum member in the generated code. For example an integer value of 6
will be converted to SIX
, or my-enum-value
will be converted to MY_ENUM_VALUE
(or the equivalent in the target language).
To have more control over the generated enum member names, you can use the x-speakeasy-enums
extension. This extension allows you to provide alternative names for each value in the enum
field.
An example of how this is used is shown below:
schema: type: integer enum: - 1 - 2 - 3 x-speakeasy-enums: - NOT_STARTED - IN_PROGRESS - COMPLETE
The order of the values in the x-speakeasy-enums
will correspond to the values in the original enum
. The provided names will then be transformed into symbols suitable for the target language.