0
0
GraphqlConceptBeginner · 3 min read

What is Inline Fragment in GraphQL: Explanation and Example

An inline fragment in GraphQL lets you conditionally select fields on different object types within a single query. It helps when querying interfaces or unions by specifying fields for specific types without separate queries.
⚙️

How It Works

Imagine you have a box with different types of toys inside, like cars and dolls. You want to ask for details about each toy, but the details differ by toy type. An inline fragment is like saying, "If the toy is a car, tell me its speed; if it's a doll, tell me its hair color." This way, you get the right details for each type in one go.

In GraphQL, when you query a field that can return multiple types (like an interface or union), you use inline fragments to specify which fields to fetch for each possible type. This avoids multiple queries and keeps your request efficient and clear.

💻

Example

This example shows a query on a SearchResult union that can be either a Book or an Author. The inline fragments fetch different fields depending on the actual type.

graphql
query {
  search(text: "GraphQL") {
    ... on Book {
      title
      pages
    }
    ... on Author {
      name
      booksWritten
    }
  }
}
Output
{ "data": { "search": [ { "title": "Learning GraphQL", "pages": 350 }, { "name": "Jane Doe", "booksWritten": 5 } ] } }
🎯

When to Use

Use inline fragments when you query fields on a type that can be one of several types, such as interfaces or unions. They let you get type-specific data in one query without asking separately for each type.

For example, if you have a feed with posts that can be images, videos, or text, inline fragments let you fetch the right details for each post type in a single request. This keeps your app fast and your code simple.

Key Points

  • Inline fragments specify fields for specific types within a query.
  • They are used with interfaces and unions to handle multiple types.
  • They keep queries efficient by avoiding multiple separate requests.
  • Syntax uses ... on TypeName { fields } inside the query.

Key Takeaways

Inline fragments let you query fields conditionally based on the object type.
They are essential when working with interfaces or union types in GraphQL.
Use inline fragments to keep queries efficient and avoid multiple requests.
The syntax is ... on TypeName { fields } inside your query.
Inline fragments help fetch type-specific data in a single query.