Enums
Enums are a special kind of type that is restricted to a particular set of values.
For example, we have a few options of ice cream available, and we want to allow user to choose only from those options.
Strawberry supports defining enums using enums from pythonβs standard library. Hereβs a quick tutorial on how to create an enum type in Strawberry:
First, create a new class for the new type, which extends class Enum:
Then, list options as variables in that class:
Finally we need to register our class as a strawberry type. Itβs done with the
strawberry.enum
decorator:
Letβs see how we can use Enums in our schema.
Defining the enum type above would produce this schema in GraphQL:
Hereβs an example of how youβd use this newly created query:
Here is result of executed query:
We can also use enums when defining object types (using strawberry.type
). Here
is an example of an object that has a field using an Enum:
And hereβs an example of how youβd use this query:
Here is result of executed query:
GraphQL types are not a map of name: value, like in python enums. Strawberry uses the name of the members of the enum to create the GraphQL type.
You can also deprecate enum value. To do so you need more verbose syntax using
strawberry.enum_value
and deprecation_reason
. You can mix and match string
and verbose syntax.