Labs ICT
Pro Login

Enums in GraphQL

Enums in GraphQL

Enums (enumerations) restrict a field to a specific set of values. They're perfect for fields that have a fixed number of options, like status, role, or category.

Enums make your API more type-safe and self-documenting. Clients know exactly what values are valid for each field.

Defining Enums

Enums are defined using the enum keyword. Each enum value is a string that represents a specific option.

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
  CANCELLED
}

enum UserRole {
  ADMIN
  USER
  MODERATOR
  GUEST
}

type Order {
  id: ID!
  status: OrderStatus!
  total: Float!
}

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

Enum values are typically SCREAMING_SNAKE_CASE, but you can use any valid GraphQL name.

Using Enums in Queries

You can use enums as arguments to filter data:

# Schema
type Query {
  orders(status: OrderStatus): [Order!]!
  users(role: UserRole): [User!]!
}

# Query for pending orders
query {
  orders(status: PENDING) {
    id
    total
    status
  }
}

# Query for admin users
query {
  users(role: ADMIN) {
    name
    email
    role
  }
}

Notice that enum values are not quoted. They're used directly as values, unlike strings which would be in quotes.

Enums in Mutations

Enums work great in mutations too, especially for setting status values:

# Mutation to update order status
mutation {
  updateOrderStatus(orderId: "123", status: SHIPPED) {
    id
    status
  }
}

# Mutation to change user role
mutation {
  updateUserRole(userId: "456", role: MODERATOR) {
    id
    name
    role
  }
}

Using enums prevents typos and invalid values. If someone tries to use an invalid status, GraphQL will reject the query.

Real-World Example

Here's a more complete example with a blog application:

enum PostStatus {
  DRAFT
  REVIEW
  PUBLISHED
  ARCHIVED
}

enum SortOrder {
  ASC
  DESC
}

enum PostField {
  TITLE
  CREATED_AT
  UPDATED_AT
  VIEWS
}

type Post {
  id: ID!
  title: String!
  status: PostStatus!
  views: Int!
  createdAt: String!
}

type Query {
  posts(status: PostStatus, sortBy: PostField, order: SortOrder): [Post!]!
}

# Query for published posts sorted by newest
query {
  posts(status: PUBLISHED, sortBy: CREATED_AT, order: DESC) {
    title
    views
  }
}

Enums make complex queries readable and ensure type safety across your API.