Docs
Launch GraphOS Studio

Using GraphQL variables in Apollo Kotlin


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

In , non-nullable are required, and nullable variables are optional. However, because variables are rarely omitted in practice, 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 , the default is to generate them as optional, but you can configure this (for specific variables or globally).

Consider the following with two nullable :

query GetTodos($first: Int, $offset: Int) {
todos(first: $first, offset: $offset) {
id
text
}
}

generates the following Kotlin code for this :

class GetTodosQuery(
val first: Optional<Int?> = Optional.Absent,
val offset: Optional<Int?> = Optional.Absent
)

You can then selectively provide or omit values like so:

// Omit values for both variables
val query = GetTodosQuery(Optional.Absent, Optional.Absent)
// Provide null for both variables
val query = GetTodosQuery(Optional.Present(null), Optional.Present(null))
// Send explicit values for both variables
val query = GetTodosQuery(Optional.Present(100), Optional.Present(0))

Making nullable variables non-optional

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

apollo {
service("service") {
// ...
generateOptionalOperationVariables.set(false)
}
}

If you do, in the case of the GetTodos shown above, now 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 variables
val query = GetTodosQuery(null, null)
// Send explicit values for both variables
val query = GetTodosQuery(100, 0)

If you pass null as the value for either of these , 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 for certain . To achieve this, you can allow optional variables on a case-by-case basis with the @optional :

query GetTodos($first: Int @optional, $offset: Int @optional) {
todos(first: $first, offset: $offset) {
id
text
}
}

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

Previous
Subscriptions
Next
Error handling
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company