In order to provide an easy-to-use, versatile API to our users, we need to understand how to leverage abstract types of modeling in addition to concrete forms.
Unions and interfaces are GraphQL abstract types that allow a schema field to return one of several object types.
A union type in GraphQL is a polymorphic type. This means that it allows many kinds to be grouped together in a single field. Consider the following schema:
type Coordinates {x: Inty: Intz: Int}type Dimensions {dimensionsType: Coordinatesdescription: String}union SearchResult = Coordinates | Dimensionstype Query {search(pattern: String): SearchResult}
In this code, SearchResult
is the union type. Various types can be modeled with the help of search results.
Interfaces allow us to define a collection of fields that we may use to make sure that all objects in our schema have fields provided in the interface. At runtime, interfaces also serve as a sort of polymorphism. We can make the type of a field an interface, which allows us to return any type that implements the interface.
interface NDimension{url: String}type Coordinate implements NDimension {X: IntY: Int}type Query {search(pattern: String): NDimension}
When a client submits a search query, the interface allows them to choose common fields. This is in contrast to unions, in which GraphQL assumes that there is no overlap between members. Interfaces, on the other hand, represent the intersection of fields between implementors and can thus be picked without qualification.
Unlock your potential: GraphQL series, all in one place!
To continue your exploration of GraphQL, check out our series of Answers below:
What is GraphQL?
Get an overview of GraphQL, its core principles, and how it enhances API interactions.
What are abstract types in GraphQL?
Understand abstract types like interfaces and unions, and how they provide flexibility in your GraphQL queries.
What are non-null constraints in GraphQL?
Discover the role of non-null constraints in ensuring data integrity within GraphQL schemas.
What are different ways to pass an argument in GraphQL?
Explore various methods for passing arguments in GraphQL to customize queries and mutations for specific needs.
GraphQL vs. REST
Compare GraphQL with REST, understanding the strengths and differences between the two approaches.
How to set up GraphQL in a React app
Learn how to integrate GraphQL into React apps to create dynamic, data-driven user interfaces.
Free Resources