Join us for GraphQL Summit, October 10-12 in San Diego. Use promo code ODYSSEY for $400 off your pass.
Launch GraphOS Studio
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

Fragments in Apollo Kotlin

Note: This article describes the behavior of s when using the default operationBased codegen in Apollo Kotlin. For the responseBased codegen, see this page.

Apollo Kotlin supports both forms of GraphQL fragments:

Named fragments

Take a look at the following GraphQL definitions:

# Declaration of named fragment
fragment launchFragment on Launch {
mission {
query LaunchDetails($id:ID!) {
launch(id: $id) {
# Usage of named fragment

Based on the fragment definition, Apollo Kotlin generates the following LaunchFragment class that you can reuse in different queries:

data class LaunchFragment(
val id: String,
val site: String?,
val mission: Mission?

Generated models for s that use this have a .launchFragment property for accessing the 's s:

println("Mission site: ${launch.launchFragment?.site}")

The launchFragment property is null if the returned object is not a Launch.

You can reuse the in any number of s:

# ...previous definitions...
query LaunchList {
launches {
launches {

You can even use a in s that are defined in a different .graphql file from the itself. This is because Apollo Kotlin codegen merges all .graphql files in to a single file before generating models.

Inline fragments

Take a look at this query definition that uses two inline s:

query HeroForEpisode($ep: Episode!) {
hero(episode: $ep) {
... on Droid {
... on Human {

For this , Apollo Kotlin generates a Hero class that contains OnDroid and OnHuman nested classes. Hero also includes onDroid and onHuman s that enable you to access fields that are specific to Droid and Human:

println("Droid primaryFunction: ${hero.onDroid?.primaryFunction}")
println("Human height: ${hero.onHuman?.height}")

These on<ShapeName> s (onDroid and onHuman) are null if the returned object is not the corresponding type.

Custom scalars
@defer support (experimental)
Edit on GitHubEditForumsDiscord