What is Enum Type in GraphQL: Definition and Usage
enum type is a special scalar that restricts a field to a set of predefined constant values. It helps ensure that only specific, allowed values are used, making your API more predictable and easier to validate.How It Works
Think of an enum type in GraphQL like a multiple-choice question where only certain answers are allowed. Instead of letting users type anything, you give them a fixed list of options to pick from. This makes it easier to control the data and avoid mistakes.
When you define an enum type, you list all the possible values it can have. Then, when clients send queries or mutations, they must use one of these values. If they try to use something else, GraphQL will reject it right away.
This is similar to choosing a color from a palette instead of mixing random colors. It keeps things simple and clear for both the server and the client.
Example
This example shows how to define an enum type for a Role in a user system. The role can only be ADMIN, USER, or GUEST.
enum Role {
ADMIN
USER
GUEST
}
type User {
id: ID!
name: String!
role: Role!
}
# Example query using the enum
query {
users {
id
name
role
}
}When to Use
Use enum types when you want to limit a field to a fixed set of values. This is helpful for things like status codes, categories, roles, or any choice where only certain options make sense.
For example, if you have a task management app, you might use an enum for task status with values like TODO, IN_PROGRESS, and DONE. This prevents invalid statuses and makes your API easier to understand and use.
Enums also improve validation and reduce bugs because clients can’t send unexpected values.
Key Points
- Enum types restrict fields to a set of predefined values.
- They improve data validation and API clarity.
- Clients must use one of the allowed enum values or the request fails.
- Enums are useful for roles, statuses, categories, and fixed options.