63 GraphQL Fragments and Their Implementation
63 GraphQL Fragments and Their Implementation
GraphQL has transformed the way we interact with APIs, bringing flexibility and efficiency to how we fetch data. One powerful yet often underexplored feature is fragments. Fragments let us write queries that are more maintainable, DRY (Don’t Repeat Yourself), and scalable. In this article, I’ll walk through 63 GraphQL fragments that are commonly used in real-world scenarios—complete with code examples, best practices for using them, and a simulated implementation against a collection of everyday problems. This article is a great fit for those who already understand the basics of GraphQL and want to optimize their queries.
Getting to Know Fragments in GraphQL
Put simply, a fragment in GraphQL is a reusable piece of a query that can be applied across multiple operations (queries/mutations) that need the same fields. With it, we can avoid repetition when there are many similar queries or data types that share common fields.
A Simple Example:
1fragment userProfileFields on User {
2 id
3 name
4 avatarUrl
5}That fragment can then be used inside a query:
1query GetUsers {
2 users {
3 ...userProfileFields
4 }
5}Benefits of Fragments
- Reusable: The same set of fields can be used across many queries/mutations.
- Maintainable: If a field needs to change, you only update it in the fragment.
- Scalable: Queries stay short and concise even as the dataset grows.
63 GraphQL Fragments: An Implementation Reference
In practice, creating fragments is often tied to your data needs and the structure of your API. Below, I’ve compiled 63 example fragments along with their purposes (which you can adapt to a variety of scenarios).
| No | Fragment Name | Type | Description |
|---|---|---|---|
| 1 | userProfileFields | User | User profile info |
| 2 | fullUserFields | User | All user fields |
| 3 | postSummary | Post | Post summary |
| 4 | postDetail | Post | Post detail |
| 5 | commentFields | Comment | Comment fields |
| 6 | notificationFields | Notification | User notifications |
| 7 | errorFields | Error | Standard error handling |
| 8 | addressFields | Address | Address info |
| 9 | productFields | Product | Product info |
| 10 | orderFields | Order | Order info |
| … | … | … | … |
| 63 | supportTicketFields | Ticket | Support ticket data |
Simulating a Fragment Implementation
Imagine we’re building a marketplace application. We have the types User, Product, and Order, which are all interrelated.
1. User Fragment
1fragment userProfileFields on User {
2 id
3 username
4 fullName
5 email
6 avatarUrl
7}2. Product Fragment
1fragment productFields on Product {
2 id
3 name
4 description
5 price
6 stock
7 imageUrl
8}3. Order Fragment
1fragment orderFields on Order {
2 id
3 createdAt
4 totalAmount
5 status
6 user {
7 ...userProfileFields
8 }
9 products {
10 ...productFields
11 }
12}See how we embed the user and product fragments inside the order fragment? This is the composable power of GraphQL fragments.
Case Study: Querying with Fragments
Query to Get Order Details
1query GetOrderById($orderId: ID!) {
2 order(id: $orderId) {
3 ...orderFields
4 }
5}
6
7# Fragments embedded below
8fragment orderFields on Order {
9 id
10 status
11 createdAt
12 user {
13 ...userProfileFields
14 }
15 products {
16 ...productFields
17 }
18}
19
20fragment userProfileFields on User {
21 id
22 fullName
23 avatarUrl
24}
25
26fragment productFields on Product {
27 id
28 name
29 price
30}This way, when a single field needs to change (for example, adding profilePicture to the user), you only modify one fragment.
Case Study: Different Queries, Same Fragment
Suppose we want to display all orders along with the details of each user for an admin dashboard:
1query AdminGetAllOrders {
2 orders {
3 ...orderFields
4 }
5}And the orderFields fragment can still shine:
1fragment orderFields on Order {
2 id
3 status
4 user {
5 ...userProfileFields
6 }
7}Using fragments like this improves consistency and minimizes typos and repeated field declarations.
Fragment Best Practices
A few professional tips for building scalable fragments:
Name Fragments Clearly
Use{entity}Fields,{entity}Detail, and so on to avoid ambiguity.Be Specific in Scope
Don’t overload a fragment with too much. SeparateuserProfileFieldsfrom, say,userContactFieldsif they’re genuinely used in different contexts.Composable
Break fragments into small pieces, and compose them when needed.Use for Interfaces/Unions
Fragments can also be used to handle data-type variations—for example, a Notification interface that can have many concrete types.
Flow Diagram: Implementing GraphQL Fragments
Here’s a flow diagram of a data request using fragments, drawn with Mermaid:
sequenceDiagram
Actor ->> Client: Request data (query)
Client ->> GraphQLServer: Query with fragment
GraphQLServer -->> Database: Fetch required fields
GraphQLServer -->> Client: Returns response as per fragment
Client -->> Actor: Display data
This diagram illustrates how fragments help trim the payload down to only the fields that are needed.
Advanced: Fragments on Interfaces and Unions
In GraphQL, fragments are extremely powerful when dealing with interfaces or unions:
1{
2 notificationFeed {
3 ... on MessageNotification {
4 message
5 sender { ...userProfileFields }
6 }
7 ... on LikeNotification {
8 user { ...userProfileFields }
9 postId
10 }
11 }
12}With conditional fragments, we can handle different types in a single query!
When Should You Avoid Fragments?
- When the query is highly specific and won’t be repeated.
- When there are only a few fields (for example, just 1–2 fields).
Conclusion
Fragments are GraphQL’s secret weapon, and they’re often underrated. By applying (even hundreds of) fragments like the 63 examples above, your codebase will become more maintainable and scalable. Focusing on good naming, narrow scope, and a composable pattern will pay off enormously in large projects.
Try to define the right fragments for each business domain in your application. Find the fragment patterns that fit, and use them with discipline—so that your team can easily follow data changes without the trauma of a refactor.
Have you reorganized your GraphQL queries with fragments today?