You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

Queries in Apollo Kotlin


Fetching data in a predictable, type-safe way is one of the core features of Apollo Kotlin. In this guide, you'll learn how to query a GraphQL endpoint and use the result in your application.

Prerequisites

This page assumes some familiarity with building GraphQL queries. For a refresher, we recommend reading this guide and practicing running queries in Apollo Sandbox.

Because Apollo Kotlin uses standard GraphQL syntax, anything query you can run in Sandbox can also be put into .graphql files in your project.

This page also assumes that you've already set up Apollo Kotlin for your Android/Kotlin application. For help with setup, see the getting started guide.

Defining

In Apollo Kotlin, each query you execute is represented as an instance of a generated class that implements the Query interface. To generate these classes, we first need to define the GraphQL operations we want to execute.

Let's say we define a GraphQL query named HeroQuery, like so:

GraphQL
HeroQuery.graphql
1query HeroQuery($id: String!) {
2  hero(id: $id) {
3    id
4    name
5    appearsIn
6  }
7}

If we define this query in its own .graphql file, Apollo Kotlin will generate a corresponding HeroQuery class that we can then use to execute the query.

To generate classes, Apollo Kotlin requires your server's schema, along with all of the .graphql files that contain your defined operations. It uses these to generate code you can use to execute queries and access typed results.

All .graphql files in your project (or the subset you specify as input to apollo-codegen if you customize the script for your code generation build phase) are combined and treated as one GraphQL document. This means that fragments defined in one .graphql file are available across all .graphql files. However, it also means that operation and fragment names must be unique (and validation errors will occur if they aren't).

Executing

To execute the query we just defined, we pass a HeroQuery instance to the query method of ApolloClient, like so:

Kotlin
1val apolloClient = ApolloClient.Builder().serverUrl("https://your.domain/graphql").build()
2val response = apolloClient.query(HeroQuery(id = "12")).execute()

By default, Apollo Kotlin offloads I/O work to a background thread, which means it's safe to start GraphQL operations on the main thread. The result is also dispatched to the calling thread, and you can use the response directly to update your data.

  • On the JVM, the I/O work is using Dispatchers.IO by default. You can change this dispatcher with ApolloClient.Builder.dispatcher.

  • On Kotlin/native (iOS, macOS, ...), the request offloads the cache and network I/O to background threads that resume in the main dispatch queue. For this reason, the ApolloClient APIs assume they are called from the main thread. It isn't possible to customize the dispatcher, but cache and network I/O are always done in background threads.

Results

A query's results are returned as a hierarchy of immutable classes that match the structure of the query's fields. These classes only include fields that are included in the query (other schema fields are omitted).

In other words, Apollo Kotlin generates classes based on the queries you write, not based on the schema you query against.

For example, given the following schema:

GraphQL
1enum Episode { NEWHOPE, EMPIRE, JEDI }
2
3interface Character {
4  id: String!
5  name: String!
6  friends: [Character]
7  appearsIn: [Episode]!
8}

And the following query:

GraphQL
1query HeroAndFriendsNames {
2  hero {
3    name
4    friends {
5      id
6      name
7    }
8  }
9}

Apollo Kotlin generates a type-safe model that looks like this (details are omitted to focus on the class structure):

Kotlin
1class HeroAndFriendsNamesQuery {
2  data class Data(val hero: Hero)
3  data class Hero(val name: String, friends: List<Friend>)
4  data class Friend(val id: String, val name: String)
5}

Because the HeroAndFriendsNames query doesn't fetch appearsIn, this property is not part of the returned result type and cannot be accessed here. Similarly, id is only accessible in Friend, not in Hero.

Because GraphQL supports nullability, you have compiled-time type safety. If the request is successful, all queried data (and only this data) will be accessible. There is no need to handle null fields in UI code.

Canceling

Operation cancellation is handled via the CoroutineScope. Canceling the current scope cancels any associated ongoing operation.

Feedback

Edit on GitHub

Forums