Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
GraphQL Union Types for Media Library
📖 Scenario: You are building a media library database that stores different types of media items: Books and Movies. Each media type has its own unique fields.To efficiently query these different media types in one request, you will use GraphQL union types.
🎯 Goal: Create a GraphQL schema that defines Book and Movie types, then create a union type called MediaItem that can represent either a Book or a Movie. Finally, define a query mediaLibrary that returns a list of MediaItem.
📋 What You'll Learn
Define a Book type with fields id (ID!), title (String!), and author (String!).
Define a Movie type with fields id (ID!), title (String!), and director (String!).
Create a union type called MediaItem that includes Book and Movie.
Define a Query type with a field mediaLibrary that returns a list of MediaItem.
💡 Why This Matters
🌍 Real World
Union types let you query different types of related data in one request, useful in media libraries, e-commerce, or social networks.
💼 Career
Understanding union types is important for building flexible GraphQL APIs that handle multiple data types efficiently.
Progress0 / 4 steps
1
Define the Book and Movie types
Create a GraphQL schema that defines a Book type with fields id of type ID!, title of type String!, and author of type String!. Also define a Movie type with fields id of type ID!, title of type String!, and director of type String!.
GraphQL
Hint
Use type keyword to define both Book and Movie types with their respective fields.
2
Create the MediaItem union type
Add a union type called MediaItem that includes Book and Movie.
GraphQL
Hint
Use the union keyword followed by the union name and the types separated by |.
3
Define the Query type with mediaLibrary field
Add a Query type with a field called mediaLibrary that returns a list of MediaItem (use square brackets).
GraphQL
Hint
Define a Query type with a field mediaLibrary that returns a list of MediaItem using square brackets.
4
Complete the schema with schema definition
Add the schema definition that sets the query root type to Query.
GraphQL
Hint
Use the schema keyword and set query: Query to complete the schema.
Practice
(1/5)
1. What is the main purpose of using union types in GraphQL?
easy
A. To group multiple object types into one field that can return different types
B. To define a list of scalar values
C. To create a new scalar type
D. To enforce a single object type for a field
Solution
Step 1: Understand union type purpose
Union types allow a field to return one of several object types, grouping them logically.
Step 2: Compare with other options
Defining a list of scalar values or creating a new scalar type describes scalars, not unions. Enforcing a single object type for a field contradicts the union concept.
Final Answer:
To group multiple object types into one field that can return different types -> Option A
Quick Check:
Union types = group multiple object types [OK]
Hint: Unions group different object types under one field [OK]
Common Mistakes:
Confusing union with scalar types
Thinking unions enforce a single type
Mixing unions with interfaces
2. Which of the following is the correct syntax to define a union type named SearchResult that includes User and Post types?
easy
A. type SearchResult = User & Post
B. union SearchResult = User | Post
C. interface SearchResult = User | Post
D. union SearchResult { User, Post }
Solution
Step 1: Recall union syntax
Unions use the syntax: union Name = Type1 | Type2 with pipe separators.
Step 2: Check each option
union SearchResult = User | Post matches correct syntax. type SearchResult = User & Post uses & which is for intersections, not unions. interface SearchResult = User | Post wrongly uses interface keyword. union SearchResult { User, Post } uses braces which is invalid for unions.
Final Answer:
union SearchResult = User | Post -> Option B
Quick Check:
Union syntax uses '=' and '|' [OK]
Hint: Use '=' and '|' to define unions, no braces [OK]
Common Mistakes:
Using '&' instead of '|'
Using braces {} instead of '='
Confusing union with interface syntax
3. Given the union type SearchResult = User | Post and this query:
{ search { ... on User { name } ... on Post { title } } }
What fields will be returned if the search result contains one User with name "Alice" and one Post with title "GraphQL Guide"?
medium
A. [{"name": "Alice"}]
B. [{"name": "Alice", "title": "GraphQL Guide"}]
C. [{"title": "GraphQL Guide"}]
D. [{"name": "Alice"}, {"title": "GraphQL Guide"}]
Solution
Step 1: Understand inline fragments on union
The query uses inline fragments to select name from User and title from Post.
Step 2: Apply to data
Since the result has one User and one Post, the response includes both objects separately with their respective fields.
Final Answer:
[{"name": "Alice"}, {"title": "GraphQL Guide"}] -> Option D
Quick Check:
Inline fragments return fields per type separately [OK]
Hint: Inline fragments return separate objects per type [OK]
Common Mistakes:
Combining fields into one object
Returning only one type's fields
Ignoring inline fragment usage
4. Consider this union definition:
union SearchResult = User | Post
And this query:
{ search { ... on User { id name } ... on Post { id title } } }
Which of the following errors will occur if you try to query a field email inside Post inline fragment like this:
{ search { ... on User { id name } ... on Post { id title email } } }
medium
A. Error: Field 'email' must be queried on User type
B. No error, query runs successfully
C. Error: Field 'email' does not exist on type 'Post'
D. Error: Union types cannot have inline fragments
Solution
Step 1: Check Post type fields
If email is not defined on Post type, querying it causes an error.
Step 2: Understand inline fragment validation
Inline fragments must only query fields existing on the specified type. Querying unknown fields causes errors.
Final Answer:
Error: Field 'email' does not exist on type 'Post' -> Option C
Quick Check:
Querying unknown fields on type causes error [OK]
Hint: Check if field exists on type before querying [OK]
Common Mistakes:
Assuming all fields exist on all union types
Thinking unions disallow inline fragments
Querying fields on wrong types
5. You have a union type SearchResult = User | Post | Comment. You want to write a query that returns the name for User, title for Post, and content for Comment. Which query correctly fetches these fields?
hard
A. { search { ... on User { name } ... on Post { title } ... on Comment { content } } }
B. { search { name title content } }
C. { search { ... on User { name } ... on Post { title } content } }
D. { search { ... on User { name } ... on Post { title } ... on Comment { title } } }
Solution
Step 1: Use inline fragments for each union type
Each type in the union requires its own inline fragment to query its specific fields.
Step 2: Validate fields per type
{ search { ... on User { name } ... on Post { title } ... on Comment { content } } } queries name on User, title on Post, and content on Comment correctly. Other options either query fields directly without fragments or use wrong fields.
Final Answer:
{ search { ... on User { name } ... on Post { title } ... on Comment { content } } } -> Option A
Quick Check:
Use inline fragments per type to query union fields [OK]
Hint: Use one inline fragment per union type with correct fields [OK]