Enums in GraphQL
Introduction
Enums, or enumerations, in GraphQL are a special type that represents a fixed set of allowed values. They provide a way to define a type that can only take on a specific set of values, which enhances type safety and improves the readability of your GraphQL API.
Defining Enums
Enums are defined in your GraphQL schema using the enum
keyword. Each value in the enum must be a unique identifier. Here's an example of how to define an enum:
enum Color {
RED
GREEN
BLUE
}
In this example, we define a Color
enum that consists of three possible values: RED
, GREEN
, and BLUE
.
Using Enums
Once defined, enums can be used in your GraphQL types (queries, mutations, or inputs). Here's how you can use the Color
enum in a type definition:
type Car {
id: ID!
color: Color!
}
In this example, the Car
type includes a color
field that accepts only values defined in the Color
enum.
When querying or mutating data, only the defined enum values can be sent:
mutation {
createCar(color: GREEN) {
id
color
}
}
Best Practices
- Use enums to represent fixed sets of values that do not change over time.
- Avoid using enums for dynamic values, such as user-generated content.
- Keep enum names descriptive to improve readability and understanding.
- Document the purpose of each enum value to aid users of your API.
FAQ
Can enums have descriptions?
Yes, you can provide descriptions for enum values to enhance documentation. For example:
enum Color {
RED @description("Represents the color red")
GREEN @description("Represents the color green")
BLUE @description("Represents the color blue")
}
Is it possible to use enums in input types?
Yes, you can use enums in input types just like in regular types:
input CarInput {
color: Color!
}