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:
query GetTodos($first: Int, $offset: Int) {todos(first: $first, offset: $offset) {idtext}}
Apollo Kotlin generates the following Kotlin code for this query:
class GetTodosQuery(val first: Optional<Int?>, val offset: Optional<Int?>)
You can then selectively provide or omit variable values like so:
// Omit values for both variablesval query = GetTodosQuery(Optional.Absent, Optional.Absent)// Provide null for both variablesval query = GetTodosQuery(Optional.Present(null), Optional.Present(null))// Send explicit values for both variablesval query = GetTodosQuery(Optional.Present(100), Optional.Present(0))
Make nullable variables non optional
To disable optional variables globally, update your Gradle config:
apollo {// ...generateOptionalOperationVariables.set(false)}
In that case, in the example of the query seen above, Apollo Kotlin generates the following code:
class GetTodosQuery(val first: Int?, val offset: Int?)
This makes the calling code less verbose to use:
// Provide null for both variablesval query = GetTodosQuery(null, null)// Send explicit values for both variablesval 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.
While doing this could simplify your code globally, you may still need to omit variables in certain cases. To that effect, optional can be opted back in on a per-variable basis, by setting the @optional
directive:
query GetTodos($first: Int @optional, $offset: Int @optional) {todos(first: $first, offset: $offset) {idtext}}
In that case, Apollo Kotlin generates code with Optional
for these specific variables even though it has been opted out globally.