0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Inline Fragments in GraphQL: Syntax and Examples

In GraphQL, use inline fragments with the syntax ... on TypeName { fields } to conditionally select fields based on the object type. This helps when querying interfaces or unions to get type-specific data within a single query.
📐

Syntax

Inline fragments use the ... on TypeName { } syntax inside a GraphQL query. The TypeName specifies the object type to conditionally select fields from. This is useful when querying interfaces or union types to get fields specific to a type.

  • ... indicates a fragment spread.
  • on TypeName specifies the type condition.
  • Curly braces { } contain the fields to select if the object matches the type.
graphql
{
  search(text: "apple") {
    __typename
    ... on Fruit {
      sweetness
      color
    }
    ... on Vegetable {
      bitterness
      color
    }
  }
}
💻

Example

This example queries a search field that returns a union of Fruit and Vegetable types. Inline fragments select fields specific to each type in one query.

graphql
query {
  search(text: "apple") {
    __typename
    ... on Fruit {
      name
      sweetness
    }
    ... on Vegetable {
      name
      bitterness
    }
  }
}
Output
{ "data": { "search": [ { "__typename": "Fruit", "name": "Apple", "sweetness": 7 }, { "__typename": "Vegetable", "name": "Artichoke", "bitterness": 5 } ] } }
⚠️

Common Pitfalls

Common mistakes when using inline fragments include:

  • Omitting the on TypeName part, which makes the fragment invalid.
  • Using inline fragments on types that are not part of the interface or union, causing errors.
  • Forgetting to include __typename when you need to know the actual type in the response.

Correct usage requires specifying the type condition and valid fields for that type.

graphql
query {
  search(text: "apple") {
    ... {
      name
    }
  }
}

# Wrong: missing 'on TypeName'

query {
  search(text: "apple") {
    ... on UnknownType {
      name
    }
  }
}

# Wrong: UnknownType not in union/interface

query {
  search(text: "apple") {
    __typename
    ... on Fruit {
      name
    }
  }
}

# Correct: includes __typename and valid type condition
📊

Quick Reference

ConceptDescriptionExample
Fragment SpreadIndicates a fragment with ...... on TypeName { fields }
Type ConditionSpecifies the type to matchon Fruit
FieldsFields selected if type matchesname, sweetness
__typenameReturns the actual type name__typename

Key Takeaways

Use inline fragments with ... on TypeName { fields } to query type-specific fields in interfaces or unions.
Always specify the correct type name in the inline fragment to avoid errors.
Include __typename in your query to identify the returned object's type.
Inline fragments let you get different fields from different types in a single query.
Omitting the 'on TypeName' or using invalid types causes query errors.