GraphQL Basics - Interfaces and Unions
Overview of Interfaces and Unions
Interfaces and unions in GraphQL allow you to define flexible types that can represent multiple structures. They are useful for building more dynamic and adaptable APIs.
Key Points:
- Interfaces enable shared fields across different types.
- Unions allow a field to return one of several different types.
- Both are powerful tools for creating complex schemas.
Defining Interfaces
An interface in GraphQL defines a set of fields that a type must include. It allows different types to implement shared functionality.
// Example: Defining an interface
interface Character {
id: ID!
name: String!
}
// Example: Implementing the interface in types
type Human implements Character {
id: ID!
name: String!
homePlanet: String
}
type Droid implements Character {
id: ID!
name: String!
primaryFunction: String
}
Using Interfaces in Queries
When querying an interface, you can use inline fragments to specify which fields to include for the different types that implement the interface.
// Example: Querying an interface
{
characters {
id
name
... on Human {
homePlanet
}
... on Droid {
primaryFunction
}
}
}
Defining Unions
A union type allows a field to return one of several different types, providing flexibility in the data returned by a query.
// Example: Defining a union
union SearchResult = Human | Droid
// Using the union in a query
type Query {
search(phrase: String!): [SearchResult]
}
Using Unions in Queries
When querying a union, you again use inline fragments to specify the specific fields to retrieve based on the type returned.
// Example: Querying a union
{
search(phrase: "Skywalker") {
... on Human {
name
homePlanet
}
... on Droid {
name
primaryFunction
}
}
}
Best Practices for Interfaces and Unions
Follow these best practices when using interfaces and unions:
- Use Interfaces for Shared Fields: Utilize interfaces to promote code reuse and maintainability.
- Keep Unions Simple: Avoid over-complicating unions; keep them focused on related types.
- Document Your Schema: Clearly document interfaces and unions to help users understand their usage.
Summary
This guide provided an overview of using interfaces and unions in GraphQL schemas. Understanding these concepts is crucial for building flexible and powerful APIs.