Heterogeneous search results
A search endpoint can return different result object shapes, such as people, droids, or spacecraft.
GraphQL · Const
A GraphQL union is an abstract output type that can resolve to one of several concrete object types. It declares no shared fields, so clients use fragments to request member-specific data.
A union is an abstract output type whose value can be one of several object types. Declare its possible object members with the union syntax, then use inline fragments or named fragments to request fields belonging to a specific member; __typename can identify the returned object type.
union SearchResult = Human | Droid | StarshipAn abstract output value resolved as one of the union's concrete object member types.
const query = `
query {
search(term: "R2-D2") {
__typename
... on Human { name }
... on Droid { name primaryFunction }
... on Starship { name length }
}
}
`;The query uses inline fragments to select fields from whichever concrete object type the union returns.
A search endpoint can return different result object shapes, such as people, droids, or spacecraft.
An API field can return one of several resource representations without forcing unrelated types to share fields.
Clients need to handle multiple concrete response types while selecting only fields valid for each type.
A union is an abstract GraphQL output type that can resolve to one of several object types. Unlike an interface, it guarantees no fields shared by those member types.
Follow-up: How would a client request member-specific data? Use inline fragments or named fragments with type conditions for each concrete object type.
Declare a union by listing its concrete object members, for example union SearchResult = Human | Droid | Starship. A returned SearchResult may be any one of those object types.
Follow-up: Can an interface be a union member? No; union members must be concrete object types.
A client cannot directly select ordinary fields on a union because the union defines no common fields. It can request __typename to identify the concrete object and use fragments to select fields on that object.
Follow-up: Why is __typename useful? It lets clients distinguish the returned member type and interpret the fragment-selected data correctly.
InterfaceInline Fragments__typenameObject types