Experience GraphQL Summit 2024: Watch On-demand →

Experience GraphQL Summit 2024: over 45+ technical sessions, real-world success stories, next-gen product demos and more. Watch On-demand →

GraphQL.com

LearnTutorialsCommunityEvents

Table of contents

    GRAPHQL BASICS

  • What is GraphQL?
  • The Query
  • Introducing Types
  • Scalars, Objects, and Lists
  • Nullability
  • Querying between Types
  • Schema
  • Enums
  • Interfaces & Unions
  • Arguments
  • Mutations
  • FAQ


Try GraphOS  
The GraphQL developer platform

Enums

When we need to constrain a field to return just one option from a set that we've defined, we can use the enumeration type—known more casually as an enum!

An enum is a structure that contains a number of different options. It won't accept just any value—instead, we restrict fields that return an enum type to always return one of the enum's options. Otherwise, they're invalid!

Let's look at an enum type that we could apply to fruits.

enum SeasonEnum {
FALL
WINTER
SPRING
SUMMER
}

Note: By convention, we write our enum's possible values in SCREAMING_SNAKE_CASE.

The SeasonEnum type contains just four options—and we can see why! When discussing the different seasons in a year, only these four choices are valid options.

Applied to a Fruit type, we can use the SeasonEnum as a field's return type.

type Fruit {
id: ID!
name: String!
seasonWhenRipe: SeasonEnum!
}

The seasonWhenRipe field that we've added to the Fruit type specifies that when we query for different kinds of fruit and their ripest seasons, the value we get back for each will be one of the following: FALL, WINTER, SPRING, or SUMMER.

Try it out with the query below!

Up Next: Interfaces & Unions

 

About

GraphQL.com is maintained by the Apollo team. Our goal is to give developers and technical leaders the tools they need to understand and adopt GraphQL.


GraphQL.com 2024