0
0
GraphqlConceptBeginner · 3 min read

What is Enum Type in GraphQL: Definition and Usage

In GraphQL, an 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.

graphql
enum Role {
  ADMIN
  USER
  GUEST
}

type User {
  id: ID!
  name: String!
  role: Role!
}

# Example query using the enum
query {
  users {
    id
    name
    role
  }
}
Output
{ "data": { "users": [ {"id": "1", "name": "Alice", "role": "ADMIN"}, {"id": "2", "name": "Bob", "role": "USER"}, {"id": "3", "name": "Eve", "role": "GUEST"} ] } }
🎯

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.
âś…

Key Takeaways

Enum types in GraphQL limit a field to specific predefined values.
They help prevent invalid data and make APIs easier to use.
Use enums for fixed sets like roles, statuses, or categories.
Clients must use one of the enum values or the query will fail.