Inline fragments let you ask for different fields depending on the type of data you get back. This helps when you have mixed types in one query.
0
0
Inline fragments in GraphQL
Introduction
When you query a list that contains different types of items and want specific fields for each type.
When you want to avoid multiple queries by getting all needed data in one request.
When your data has optional fields that only exist on some types.
When you want to keep your query simple but still get detailed info for different types.
Syntax
GraphQL
query {
someField {
... on TypeName {
field1
field2
}
... on AnotherType {
fieldA
fieldB
}
}
}Use ... on TypeName inside your query to specify fields for that type.
Inline fragments help when the server returns different types in the same field.
Examples
This query asks for
name and email if the item is a User, or title and price if it is a Product.GraphQL
query {
searchResults {
... on User {
name
email
}
... on Product {
title
price
}
}
}This query gets a common
message for all notifications, but also gets severity if it is an Alert, or remindAt if it is a Reminder.GraphQL
query {
notifications {
message
... on Alert {
severity
}
... on Reminder {
remindAt
}
}
}Sample Program
This query fetches a list of items. For each item, it always gets the id. If the item is a Book, it also gets the title and author. If it is a Movie, it gets the title and director.
GraphQL
query {
items {
id
... on Book {
title
author
}
... on Movie {
title
director
}
}
}OutputSuccess
Important Notes
Inline fragments only work when the server schema supports multiple types for a field.
You can mix inline fragments with common fields outside them.
Summary
Inline fragments let you get different fields based on the data type.
They help when querying mixed-type lists or unions.
Use ... on TypeName inside your query to specify fields for each type.