0
0
GraphQLquery~30 mins

Inline fragments in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Inline Fragments in GraphQL Queries
📖 Scenario: You are building a GraphQL query to fetch data about different types of media items in a library. The library contains Books and Movies. Each type has some common fields and some unique fields.For example, both Books and Movies have id and title. Books have author and pageCount, while Movies have director and duration.
🎯 Goal: Create a GraphQL query that fetches the id and title for all media items, and uses inline fragments to fetch the specific fields for Books and Movies.
📋 What You'll Learn
Create a query named GetMediaItems
Fetch id and title for all media items
Use inline fragments to fetch author and pageCount for Books
Use inline fragments to fetch director and duration for Movies
💡 Why This Matters
🌍 Real World
GraphQL APIs often return data from interfaces or unions where different types share some fields but also have unique fields. Inline fragments let you fetch the right fields for each type in one query.
💼 Career
Understanding inline fragments is essential for working with GraphQL APIs in frontend or backend development, enabling you to write efficient and precise queries.
Progress0 / 4 steps
1
Create the base query for media items
Write a GraphQL query named GetMediaItems that fetches the id and title fields from mediaItems.
GraphQL
Need a hint?

Start by writing a query that fetches the common fields id and title for all media items.

2
Add inline fragment for Books
Inside the mediaItems field, add an inline fragment for Book that fetches the author and pageCount fields.
GraphQL
Need a hint?

Use ... on Book { author pageCount } inside mediaItems to fetch book-specific fields.

3
Add inline fragment for Movies
Inside the mediaItems field, add an inline fragment for Movie that fetches the director and duration fields.
GraphQL
Need a hint?

Use ... on Movie { director duration } inside mediaItems to fetch movie-specific fields.

4
Complete the query with all inline fragments
Ensure the query GetMediaItems fetches id and title for all media items, and uses inline fragments for Book and Movie to fetch their specific fields.
GraphQL
Need a hint?

Review your query to make sure all parts are included and correctly structured.