GraphQL Interface Type: Definition, Usage, and Examples
interface type defines a set of fields that multiple object types can share. It acts like a contract that ensures these object types implement the same fields, enabling flexible and consistent querying across different types.How It Works
Think of a GraphQL interface as a shared blueprint or contract that multiple object types agree to follow. Just like in real life, where different devices might share the same charging port type, in GraphQL, different object types can share the same fields defined by an interface.
This means you can write queries that ask for fields defined in the interface, and GraphQL will return data from any object type that implements that interface. It helps keep your API organized and consistent, especially when you have different types that share common features.
Example
This example shows a GraphQL interface called Character with fields id and name. Two object types, Human and Droid, implement this interface. You can query for Character fields and get results from both types.
interface Character {
id: ID!
name: String!
}
type Human implements Character {
id: ID!
name: String!
homePlanet: String
}
type Droid implements Character {
id: ID!
name: String!
primaryFunction: String
}
# Sample query
query {
characters {
id
name
... on Human {
homePlanet
}
... on Droid {
primaryFunction
}
}
}When to Use
Use GraphQL interface types when you have multiple object types that share common fields but also have their own unique fields. This helps you write flexible queries that can work with different types in a consistent way.
For example, in a game or movie API, characters might be humans, droids, or aliens, but all share basic info like id and name. Interfaces let you query these shared fields without needing separate queries for each type.
Key Points
- An
interfacedefines common fields for multiple object types. - Object types must implement all fields declared in the interface.
- Interfaces enable flexible queries that work across different types.
- Use interfaces to keep your schema organized and avoid repeating fields.