Heterogeneous search results
A search endpoint can return different result objects such as people, ships, or droids.
GraphQL · Class
A GraphQL union is an abstract output type that can resolve to one of several concrete object types. It defines no shared fields, so clients use inline fragments to request member-specific data.
A GraphQL union is an abstract output type whose value can be one of several concrete object types. Since the union declares no shared fields, clients use inline fragments for member-specific fields and may use __typename to identify the concrete result.
union SearchResult = Human | Droid | StarshipAn object value whose concrete type is one of the union's declared member Object types.
const query = `
query {
search(text: "R2-D2") {
__typename
... on Droid { name primaryFunction }
... on Human { name homePlanet }
... on Starship { name length }
}
}
`;Use inline fragments to request fields from whichever concrete object a union field returns.
A search endpoint can return different result objects such as people, ships, or droids.
A field can expose several unrelated object shapes while preserving a single return type.
A client needs to render different data for each returned concrete object type.
A union represents a value that may be one of several object types, without guaranteeing fields common to all of them. Its members are listed explicitly in the schema.
Follow-up: How does a client read member-specific data? Use an inline fragment for each possible concrete object type.
A union has no shared fields, so fields defined by its member objects cannot be selected directly from the union. Inline fragments narrow the selection to a particular member type.
Follow-up: What metadata can be requested without narrowing? The __typename meta-field identifies the concrete object type returned.
A union is declared by listing its possible object types, such as union SearchResult = Human | Droid | Starship. A field returning it may therefore produce any listed member.
Follow-up: Can an interface be used as a union member? No; union members must be concrete object types.
Interfaceinline fragments__typenameObject types