Using GraphQL variables in Apollo Kotlin


GraphQL supports passing argument values to your operations with variables. This enables you to write a single query that you can reuse with multiple variable values (this is a recommended best practice).

In GraphQL, non-nullable variables are required, and nullable variables are always optional. Apollo Kotlin uses its own Optional type to distinguish between present (but maybe nullable) and absent types.

Consider the following GraphQL query with two nullable variables:

GraphQL
1query GetTodos($first: Int, $offset: Int) {
2  todos(first: $first, offset: $offset) {
3    id
4    text
5  }
6}

Apollo Kotlin generates the following Kotlin code for this query:

Kotlin
1class GetTodosQuery(
2    val first: Optional<Int?> = Optional.Absent,
3    val offset: Optional<Int?> = Optional.Absent
4)

You can then selectively provide or omit variable values like so:

Kotlin
1// Omit values for both variables
2val query = GetTodosQuery(Optional.Absent, Optional.Absent)
3// Provide null for both variables
4val query = GetTodosQuery(Optional.Present(null), Optional.Present(null))
5// Send explicit values for both variables
6val query = GetTodosQuery(Optional.Present(100), Optional.Present(0))

Using input builders

For both operations and input objects, having to wrap values in an Optional wrapper can be cumbersome.

For those cases, use generateInputBuilders:

Kotlin
1apollo {
2  service("service") {
3    // ...
4    generateInputBuilders.set(true)
5  }
6}

If you do, in the case of the GetTodos query shown above, Apollo Kotlin now generates a Builder for each operation:

Kotlin
1// Omit values for both variables
2val query = GetTodosQuery.Builder()
3               .build()
4// Provide null for both variables
5val query = GetTodosQuery.Builder()
6               .first(null)
7               .offset(null)
8               .build()
9// Send explicit values for both variables
10val query = GetTodosQuery.Builder()
11               .first(100)
12               .offset(0)
13               .build()
Feedback

Edit on GitHub

Forums