Published on February 12, 2025
Using GraphQL simplifies fetching data for your application, which gives you back more time to focus on improving your application's performance. GraphQL fragments are a way of breaking down parts of your GraphQL queries into modular components, making your queries more readable and maintainable, and reducing redundancy.
GraphQL fragments simplify the management of complex queries. They do this for different queries and for nested objects, by allowing parts of a query to be reused across multiple queries. The obvious analogy is with using a function to avoid duplication of code — “copypasta.”
This article explains the benefits of GraphQL fragments and the different ways to use them. We will take a look at some simple examples, then build on them to provide realistic scenarios for your applications.
GraphQL fragments are snippets of GraphQL queries that keep your queries clean and make them easier to maintain — especially when dealing with deep or repeating data structures.
One of the main benefits of GraphQL APIs is that they are faster than traditional RESTful endpoints because you get back just what you need from a single, flexible endpoint.
However, because of this, GraphQL queries can grow quickly and become messy and hard to read. Fragments help by introducing pieces of queries that are easier to use and to read.
In this article, we will make use of the Star Wars GraphQL API explorer, a public API with a GraphQL explorer that doesn’t require registration, to illustrate the use of fragments and how they can simplify your queries. You can open the GraphQL explorer and paste in the queries in this article to get immediate API responses.
Below you can see a GraphQL fragment example. We start with a simple but bloated query, and show how a GraphQL fragment makes the query shorter and more readable.
As you can see from the example above, the syntax is quite straightforward. Here it is in pseudo-code.
Fragments can use other fragments, making them nested fragments.
The Type of the fragment specifies which data type the fragment can be used with. This prevents fields being used for types they are not present on. In the Star Wars example above, the fragment is used on the type Person, meaning it can use any fields available to a Person in this API. If your GraphQL has defined any interfaces, you can also declare an interface as the type, allowing you to use fields across a range of types.
There are a number of different ways to use GraphQL fragments, which we cover below. To start, GraphQL fragments can be shared across GraphQL queries, fields, or aliases.
A fragment can be reused across multiple queries, which can be useful if your application has multiple queries that share similar fields. To do this, you define a fragment and refer to it inside from within other queries. Note that the Star Wars GraphQL API explorer doesn't allow two queries to be run at the same time, but it's still possible to define two separate queries in your code that reuse a fragment.
Query 1: Fetch a single Star Wars character.
Query 2: Fetch a Star Wars character along with their starship pilot.
If your query needs to return two fields of the same object type, you need to use aliases. Fragments can be used within an alias, though you cannot directly alias a fragment. The example below reuses the PersonDetails
fragment, as above with luke
and leia
, this time inside two different aliases (hero and villain, which are both of type person).
This will return named properties on the response, because of the aliases.
We can use the same PersonDetails
fragment above and share it between different fields in the same query.
This will return the id
and name
fields of a Person object for both Luke and Leia.
Fragments don't directly accept arguments; however, you can pass an argument to a field inside a fragment.
The example below passes the argument first: 1
to the starshipConnection
field. This is a cursor-based pagination argument that retrieves the first starship associated with a Person.
You can use this fragment just like you used PersonDetails
from before.
This query retrieves the person’s details and their first starship. The component object within the Person
object is used within the fragment just as it would if this were all inline.
Inline fragments work slightly differently to normal fragments, but they also work to make GraphQL more modular and type-specific. Inline fragments are used whenever a union or interface is used, for example, to retrieve information from a list of disparate types.
The Star Wars API defines an interface called Node that is implemented by almost every type in the system. The query below uses inline fragments (these are the fields preceded with ‘...’) to retrieve an object of any type and pull the relevant fields from each as necessary.
The use of __typename
tells the client which type was actually returned, reducing ambiguity. The query above would return the following:
Nesting fragments involves having one fragment inside another. For example, you could have a fragment for the details of a Star Wars character's home planet, and then use this fragment inside the original PersonDetails
fragment, which is then in turn used by a GraphQL query.
Just like reusable functions in code, fragments introduce reusability into GraphQL. This allows you to avoid repeating code, making your queries DRY.
You’ll notice that fragments are individually named, making your code cleaner, more readable, and easier to maintain. A top-level query can now include great detail, with each segment being sensibly named and simpler to understand at a glance.
This more readable code brings with it the single responsibility principle, which means you can update one central piece of code and know that everywhere using it receives the benefit.
Fragments also help you reduce over-fetching, because they make it easier to see which code will be requesting what data, and remove it if it’s not needed. This can lead to great performance improvements when refactoring old queries.
Using fragments can improve performance even more if you combine them with GraphQL directives such as @include or @skip, which allow you to include or exclude certain fragments dynamically at runtime based on variables.
Here’s how to conditionally use a fragment with a directive. First, define a variable.
Then apply the directive to the fragment.
GraphQL clients, like Relay and Apollo Client, use fragments to improve caching. They minimize redundant network calls by implementing partial data retrieval. Where a fragment has been used to retrieve an element of a previous request, it is cached as a subset of data and can be returned as part of a later response.
Here’s some guidance on how to keep your fragments well written and reusable.
When writing GraphQL fragments, it’s important to keep them focused on their specific use case. You should always keep your fragments restricted to their atomic business unit of data, rather than mixing fields from unrelated entities. For example, vehicles and people are distinct concepts, so would ideally have their own fragments rather than mixing data from both in the same fragment.
Avoid overly broad fragments and never add fields just in case. This falls under the YAGNI maxim — You Aren’t Going to Need It. Doing so will likely complicate development down the road and confuse your future self or colleagues.
While nesting is a powerful tool, avoid deeply nested fragments as they will fall to the same fate, becoming too complex and hard to debug.
Another good tip is to colocate your fragments with their relevant code components, rather than storing them all in one place. If you've got fragments that are being reused across different places, you can store them in a separate file and import that file when you need to use them.
GraphQL helps you scale your applications by providing a single API endpoint that’s as flexible as you need it to be. This helps developers access what they need so they can build the interfaces users want, and it keeps applications running fast by minimizing unnecessary network traffic and providing efficient data processing. Client libraries like Apollo and Relay can also help you by providing intelligent caching, thereby lightening the load on the server.
If you're working with content-heavy applications, GraphQL fragments will help you manage your queries as they grow in size. You may also benefit from using the Contentful® Composable Content Platform, which is designed for large volumes of content and has a comprehensive GraphQL API that works with fragments.
Contentful helps you organize your content into a well-structured content model, and even supports multiple teams working on the same model. Its optimized APIs deliver content quickly, even during high traffic, by utilizing its global CDN. Try out Contentful and its GraphQL API by signing up today.
Subscribe for updates
Build better digital experiences with Contentful updates direct to your inbox.