In this tutorial, we'll explore Enums and Interfaces in GraphQL. These special types provide more flexibility and abstraction in your GraphQL schema. By the end, you will understand when and how to use them for best results.
You will learn:
- What Enums and Interfaces are in GraphQL
- How to define and use them
- Best practices for working with Enums and Interfaces
Prerequisites:
- Basic understanding of GraphQL and its schema
- Basic programming knowledge
In GraphQL, Enums, or Enumerations, are a special kind of scalar that is restricted to a specific set of allowed values. This allows you to:
Here's an example:
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
Interfaces are abstract types that allow you to define fields that multiple types will have in common. They are useful when you have a group of related types that share common fields.
Here's an example:
interface Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
}
enum Status {
ACTIVE
INACTIVE
SUSPENDED
}
type User {
id: ID!
name: String!
status: Status!
}
In this example, we have a Status
Enum with values ACTIVE, INACTIVE, and SUSPENDED. In the User
type, the status
field must be one of the values defined in the Status
Enum.
interface Vehicle {
maxSpeed: Int!
}
type Car implements Vehicle {
maxSpeed: Int!
seats: Int!
}
type Plane implements Vehicle {
maxSpeed: Int!
wingspan: Int!
}
Here, both Car
and Plane
types implement the Vehicle
interface. Hence, they both have a maxSpeed
field. Additionally, Car
has a seats
field and Plane
has a wingspan
field.
In this tutorial, we covered Enums and Interfaces in GraphQL. You learned what they are, how to define and use them, and some best practices.
Your next steps could include diving deeper into other special types in GraphQL, such as Unions and Input types, or exploring more advanced features like mutations and subscriptions.
Schedule
type.Animal
interface with fields name
and age
, and implement it in Dog
and Cat
types.enum Day {
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
}
type Schedule {
day: Day!
event: String!
}
Animal
interface:interface Animal {
name: String!
age: Int!
}
type Dog implements Animal {
name: String!
age: Int!
breed: String!
}
type Cat implements Animal {
name: String!
age: Int!
color: String!
}
Keep practicing to understand Enums and Interfaces better. Try to use them in your own GraphQL schemas. Happy learning!