GraphQL Fragments
# CHAPTER 12
GraphQL Fragments
1. Introduction
As your application grows, your GraphQL queries will become larger and more complex. You will likely find yourself requesting the exact same set of fields in multiple different queries across your application. In software engineering, we follow the DRY principle (Don't Repeat Yourself). In this chapter, we will introduce Fragments, a powerful feature of GraphQL that allows you to create reusable pieces of query logic, making your frontend code cleaner, more maintainable, and less prone to errors.2. Learning Objectives
By the end of this chapter, you will be able to:- Define what a GraphQL Fragment is.
- Understand the syntax for creating and spreading fragments in queries.
- Apply fragments to keep frontend queries DRY.
- Utilize Inline Fragments for working with interfaces or union types.
3. Beginner-Friendly Explanation
Imagine you are a frequent traveler. You have a specific list of essentials you pack every time: passport, toothbrush, and phone charger. Instead of writing out that entire list every time you plan a trip to a new city, you create a sticky note called "Travel Essentials."When you plan a trip to Paris, your packing list just says: "Clothes, Camera, + *[Travel Essentials]*". When you go to Tokyo, your list says: "Business Suit, Laptop, + *[Travel Essentials]*".
A Fragment is that sticky note. It is a reusable list of fields that you can insert (or "spread") into any query that needs them, rather than typing out id, name, email, avatarUrl every single time you query a User.
4. Real-World Examples
-
UI Components: In modern frameworks like React, you build a
UserProfileCardcomponent. You define a fragment containing the exact fields that card needs. Whenever a parent component queries data, it just includes theUserProfileCardfragment, ensuring the component always gets the data it requires.
-
Standardized Responses: If you have multiple mutations (e.g.,
updateUser,changePassword,updateAvatar), they all likely return the updated User object. Instead of writing the same 10 fields in every mutation response, you use aUserDetailsfragment.
5. Detailed Code Examples
Let's see how fragments are created and used.The Problem (Repetitive Code):
The Solution (Using a Fragment):
We define a fragment using the fragment keyword, give it a name, and specify which Type it belongs to using the on keyword.
6. Mutation Examples with Fragments
Fragments are incredibly useful in mutation responses to ensure consistency.7. Inline Fragments (Advanced)
Sometimes a GraphQL API returns a list that contains different *types* of objects (like a feed containing bothPhotos and Articles). How do you query specific fields when you don't know what type will be returned? You use an Inline Fragment.
8. Schema Requirements for Fragments
You do not define fragments in your server's Schema SDL! Fragments are purely a client-side construct. The server understands them as long as the type specified after theon keyword exists in the schema.
9. Best Practices
-
Name Fragments Clearly: A fragment name should describe its purpose or the UI component it fuels, e.g.,
AuthorCardDetailsorNavMenuUser.
- Co-locate Fragments: If you are using a component-based frontend framework (Vue/React), define the fragment in the exact same file as the component that uses it.
- Don't Over-Fragment: If a fragment is only used once, there is no need to create it. Only extract fields into a fragment if they are reused in multiple places.
10. Common Mistakes
-
Forgetting the
onkeyword: A fragment *must* declare what Schema Type it belongs to (e.g.,fragment Details on Product).
-
Spreading on the wrong type: You cannot use
...CoreUserInfo(which is onUser) inside a query that returns aProduct. GraphQL will throw a validation error.
11. Mini Exercises
- 1. What three characters are used to "spread" a fragment into a query?
-
2.
Look at this definition:
fragment ItemDetails on Product { price }. What doesProductrepresent?
12. Coding Challenges
Challenge 1:-
1.
Create a fragment called
BookSummaryon theBooktype that includestitleandisbn.
-
2.
Write a query called
GetLibrarythat fetchesallBooks, and spread yourBookSummaryfragment inside the selection set.
13. MCQs with Answers
What is the primary purpose of a GraphQL Fragment?
Which symbol is used to include (spread) a fragment within a query?
When querying an array that contains multiple different object types (like a timeline), what feature must you use?
14. Interview Questions
- Q: Explain the concept of DRY code and how GraphQL Fragments help achieve it.
- Q: Where are fragments defined: on the server's Schema or by the frontend client?
- Q: What is an Inline Fragment and in what specific scenario is it used?
15. FAQs
Q: Can a fragment include another fragment inside it? A: Yes! This is called nesting fragments. It is highly encouraged when building complex UI components that are made up of smaller sub-components.Q: Are fragments sent to the server? A: Yes. When the client makes the HTTP request, the fragment definitions are sent alongside the query string so the server can parse and expand them before executing.
16. Summary
In this chapter, we tackled query optimization and code cleanliness by introducing Fragments. We learned how to define reusable blocks of fields using thefragment and on keywords, and how to inject them into Queries and Mutations using the spread operator (...). We also touched on Inline Fragments, a powerful tool for querying mixed-type arrays like social media feeds.