0
0
GraphQLquery~5 mins

Union types in GraphQL

Choose your learning style9 modes available
Introduction

Union types let you combine different object types into one. This helps when a field can return different kinds of data.

When a query can return different types of objects, like a search returning books or authors.
When you want to handle multiple related types in one response.
When you need to simplify your schema by grouping types that share no common fields.
When you want to write flexible queries that adapt to different data shapes.
Syntax
GraphQL
union SearchResult = Book | Author | Magazine
Union types list multiple object types separated by | (pipe).
Each type in the union must be an object type, not a scalar or interface.
Examples
This union type groups Photo and Video types under Media.
GraphQL
union Media = Photo | Video
SearchResult can be a User, a Post, or a Comment.
GraphQL
union SearchResult = User | Post | Comment
Sample Program

This example defines a union SearchResult that can be a Book or an Author. The query searches and handles both types separately.

GraphQL
type Book {
  title: String
  author: String
}

type Author {
  name: String
  books: [Book]
}

union SearchResult = Book | Author

# Query example
query {
  search(keyword: "GraphQL") {
    ... on Book {
      title
      author
    }
    ... on Author {
      name
    }
  }
}
OutputSuccess
Important Notes

When querying a union type, use inline fragments (... on TypeName) to access fields of each type.

Union types cannot have fields themselves; only the member types have fields.

Summary

Union types group multiple object types into one.

Use unions when a field can return different object types.

Query unions with inline fragments to get data from each type.