0
0
GraphQLquery~30 mins

Union types in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the schema keyword and set query: Query to complete the schema.