Schema

GraphQL Enums

Using Enum Types

GraphQL enums define fixed sets of allowed values.

What are GraphQL Enums?

In GraphQL, an enum (short for enumeration) is a special scalar type that represents a set of named values. Enums are useful when you need to define a type with a limited set of possible values. This makes your schema more understandable and helps avoid errors by limiting the values that can be assigned to a field.

Defining Enums in a Schema

To define an enum in your GraphQL schema, you use the enum keyword followed by the name of the enum and the possible values it can take. Here’s a basic example:

In this example, the Status enum includes three possible values: ACTIVE, INACTIVE, and SUSPENDED. These values are constant and cannot be changed at runtime.

Using Enums in Queries

Enums can be used as input in queries to specify certain values. Here’s how you can use the Status enum in a query:

In this query, we request the status of a user by their ID. The status field is expected to return one of the predefined enum values: ACTIVE, INACTIVE, or SUSPENDED.

Using Enums in Mutations

Enums are also useful in mutations, where you can set a field to one of the enum's values. Here’s an example of a mutation that updates a user’s status:

In this mutation, we’re updating the status of a user by passing a value of the Status enum. The $status variable must be one of the enum values: ACTIVE, INACTIVE, or SUSPENDED.

Why Use Enums?

Enums help enforce strict typing and prevent invalid data from being passed into your GraphQL API. By limiting the possible values for a field, you increase the reliability and predictability of your API. Additionally, enums improve the readability and maintainability of your schema, making it easier for developers to understand the constraints of your application.

Previous
Unions