Skip to content
Santekno.com | Tech Tutorials and Trends
EN
📖 0%
01 Sep 2025 · 5 min read ·Article 63 / 125
Go

63 GraphQL Fragments and Their Implementation

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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:

graphql
1fragment userProfileFields on User {
2  id
3  name
4  avatarUrl
5}

That fragment can then be used inside a query:

graphql
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).

NoFragment NameTypeDescription
1userProfileFieldsUserUser profile info
2fullUserFieldsUserAll user fields
3postSummaryPostPost summary
4postDetailPostPost detail
5commentFieldsCommentComment fields
6notificationFieldsNotificationUser notifications
7errorFieldsErrorStandard error handling
8addressFieldsAddressAddress info
9productFieldsProductProduct info
10orderFieldsOrderOrder info
63supportTicketFieldsTicketSupport ticket data
Danger
Note: The table above is a template. Fragments will be specific to your application’s domain. We’ll cover a few implementations later on.

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

graphql
1fragment userProfileFields on User {
2  id
3  username
4  fullName
5  email
6  avatarUrl
7}

2. Product Fragment

graphql
1fragment productFields on Product {
2  id
3  name
4  description
5  price
6  stock
7  imageUrl
8}

3. Order Fragment

graphql
 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

graphql
 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:

graphql
1query AdminGetAllOrders {
2  orders {
3    ...orderFields
4  }
5}

And the orderFields fragment can still shine:

graphql
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:

  1. Name Fragments Clearly
    Use {entity}Fields, {entity}Detail, and so on to avoid ambiguity.

  2. Be Specific in Scope
    Don’t overload a fragment with too much. Separate userProfileFields from, say, userContactFields if they’re genuinely used in different contexts.

  3. Composable
    Break fragments into small pieces, and compose them when needed.

  4. 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:

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:

graphql
 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?


Related Articles

💬 Comments