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 optional. However, because variables are rarely omitted in practice, Apollo Kotlin provides a mechanism to make variables non-optional in generated code. This makes the structure of generated code more straightforward.

Because you might still need to omit variables, the default is to generate them as optional, but you can configure this (for specific variables or globally).

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))

Making nullable variables non-optional

To disable optional variables globally, update your Gradle config like so:

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

If you do, in the case of the GetTodos query shown above, Apollo Kotlin now generates the following code:

Kotlin
1class GetTodosQuery(val first: Int?, val offset: Int?)

This makes the calling code less verbose to use:

Kotlin
1// Provide null for both variables
2val query = GetTodosQuery(null, null)
3// Send explicit values for both variables
4val query = GetTodosQuery(100, 0)

If you pass null as the value for either of these variables, Apollo Kotlin sends null to the server as the value of that variable instead of omitting it entirely.

Although doing this can simplify your code in most cases, you might still need to omit variables for certain operations. To achieve this, you can allow optional variables on a case-by-case basis with the @optional directive:

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

In this case, Apollo Kotlin generates code with Optional for only these specific variables.

Feedback

Edit on GitHub

Forums