Schema
GraphQL Interfaces
Using Interfaces
GraphQL interfaces define shared fields for polymorphic types.
What is a GraphQL Interface?
In GraphQL, interfaces are used to describe a set of fields that multiple types can share. An interface can be thought of as a contract that any implementing type must adhere to, meaning each type must provide implementations for the fields defined in the interface.
This mechanism allows for polymorphism in your GraphQL schema, enabling a common structure across different types that implement the interface.
Defining a GraphQL Interface
To define an interface in GraphQL, you use the interface
keyword followed by the interface name and fields. Each field must have a type, and the implementing types must include all the fields specified in the interface.
Implementing Interfaces in Types
Once an interface is defined, you can create types that implement this interface. The implementing types must include all fields defined in the interface and can also have additional fields specific to them.
Querying with Interfaces
When querying fields that are defined on an interface, you can retrieve shared fields across all types implementing the interface. Additionally, you can use inline fragments to access fields that are specific to a particular type.
Benefits of Using Interfaces
Using interfaces in GraphQL offers several advantages:
- Code Reusability: Define shared fields once and reuse them across multiple types.
- Polymorphic Queries: Write queries that interact with multiple types through a single interface.
- Consistency: Ensure all implementing types adhere to a common structure.