GraphQL Fragments and Variables: Advanced Query Techniques

GraphQL fragments & variables title card

In our introduction to GraphQL basics, we covered how it enables clients to request exactly the data they need—and nothing more. That alone is a huge win over the REST API, but there’s more power under the hood.


In this post, we’ll step beyond the basics and look at two core concepts that help make your queries both flexible and maintainable: GraphQL variables and GraphQL fragments. We’ll also show how to run and test these queries using Postman, so you can work with live data and get comfortable using these features in practice.


Understanding GraphQL Variables and Filters

Hardcoding values into a query is fine for quick tests. But in real-world apps, you want your queries to be dynamic. That’s where GraphQL variables come in. Instead of embedding parameters directly into your query string, you define placeholders that get their values at runtime.
Here’s a simple example without variables:

				
					query {
  user(id: "123") {
    name
    email
  }
}

				
			

Now here’s the same query using variables:

				
					query GetUser($userId: ID!) {
  user(id: $userId) {
    name
    email
  }
}

				
			

And you pass the variable like this:

				
					{
  "userId": "123"
}

				
			

Why use variables? A few reasons:

  • Security: Keeps input values separate from the query, which is especially useful when sending queries over HTTP.
  • Reusability: Makes it easier to reuse the same query structure with different inputs.
  • Clean code: Keeps your query templates neat and readable.


Filtering with variables

Variables also shine when you need to filter results. Let’s say you’re querying a list of blog posts and want only those published after a certain date:

				
					query GetRecentPosts($after: String!) {
  posts(filter: { publishedAfter: $after }) {
    title
    publishedAt
  }
}

				
			

And your variable payload:

				
					{
  "after": "2023-01-01"
}

				
			

This approach makes your query adaptable to user input, pagination, search functionality, and more—all without changing the query structure itself.

Working with GraphQL Fragments: Polymorphism and Inline Power

Fragments are a powerful feature in GraphQL for structuring queries and avoiding repetition—but their true strength shows up when dealing with polymorphic types.


Let’s say your schema includes a generic type, like Person, which could represent different roles: User, Author, or Admin. These roles may share common fields, but also have role-specific attributes. Inline fragments let you conditionally request fields based on the actual type of the object returned at runtime.


Here’s an example:

				
					query {
  people {
    id
    name
    ... on User {
      email
      joinedDate
    }
    ... on Author {
      articlesCount
    }
    ... on Admin {
      accessLevel
    }
  }
}


				
			

This is where inline fragments shine. Without them, you’d either over-fetch fields that don’t exist on certain types, or miss out on key details. Inline fragments make your queries flexible and type-safe, especially in systems where different object types share an interface or union but expose distinct properties.

Why Inline Fragments Matter

  • Handle polymorphic types: Useful when dealing with generic interfaces or unions that represent multiple types.
  • Access type-specific fields: Request only the fields that apply to a given runtime type.
  • Reduce complexity: Keep your queries readable without nesting multiple query paths.
  • Improve frontend data modeling: Ideal for component-based UIs where different components may expect different data shapes based on type.

In platforms where generic data models or runtime type differentiation are common, inline fragments provide a clean and maintainable way to query for just the right data—no more, no less.

Querying With Postman

You don’t need a full frontend or GraphQL dev environment to test your queries—Postman is an excellent tool for exploring GraphQL APIs. Here’s how to use it with GraphQL fragments and variables.

1. Set the HTTP Method and Headers

  • Method: POST
  • URL: Your GraphQL endpoint, e.g., https://api.example.com/graphql
  • Headers:
    • Content-Type: application/json
    • Add any required authorization headers


2. Structure the body

Use the “raw” body mode in Postman and set it to JSON. Your request body should include:

				
					{
  "query": "query GetUser($userId: ID!) { user(id: $userId) { ...UserFields } } fragment UserFields on User { id name email }",
  "variables": {
    "userId": "123"
  }
}

				
			

Note that the query string includes both the query and the fragment—Postman doesn’t support separate fragment files, so you include everything in one string.

3. Send the request

Hit Send and inspect the response. You can tweak your variables and see how your query behavior changes, making it a great way to test filters, edge cases, or new schema additions.

GraphQL Fragments and Variables in Infrahub

To give you even greater power when querying data, the syntax for working in GraphQL in Infrahub is a little different than the standard syntax.

In the video below, CEO Damien Garros explores GraphQL variables (including defaults) and GraphQL fragments from the Infrahub interface. Then at 11:25, Damien talks you through querying GraphQL with Postman.

Wrapping Up

GraphQL variables and fragments are small tools with big impact. Variables make your queries dynamic and flexible, while fragments help you write cleaner, more maintainable code. And tools like Postman make it easy to test and iterate without a full dev environment.

If you’re comfortable with these concepts, you’re well on your way to writing robust GraphQL queries.

Helpful Resources

Share the Post:

JOIN OUR MAILING LIST

Please enter your email address to stay informed about OpsMill developments. Your email address will be stored according to GDPR and will never be sold.

REQUEST A DEMO

See OpsMill in action and learn how it can help you achieve your goals. Fill out the form below to schedule a personalized demo.

By submitting this form, you agree that your personal data will be stored and processed by OpsMill in accordance with our privacy policy.