Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL Federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free

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 GraphQL, non-nullable are required, and nullable variables are always optional. uses its own Optional type to distinguish between present (but maybe nullable) and absent types.

Consider the following GraphQL query with two nullable variables:

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

Apollo Kotlin generates the following Kotlin code for this query:

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

You can then selectively provide or omit variable 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))

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:

apollo {
service("service") {
// ...
generateInputBuilders.set(true)
}
}

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

// Omit values for both variables
val query = GetTodosQuery.Builder()
.build()
// Provide null for both variables
val query = GetTodosQuery.Builder()
.first(null)
.offset(null)
.build()
// Send explicit values for both variables
val query = GetTodosQuery.Builder()
.first(100)
.offset(0)
.build()
Previous
Subscriptions
Next
Error handling
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company