Subchapter 5.4
references/setup.mdMarkdown3 KBView on GitHub
Use this guide to setup Apollo Kotlin and configure code generation and schema downloads.
scripts/list-apollo-kotlin-versions.sh and pick the latest releaseAdd the Apollo Kotlin Gradle plugin:
plugins {
// Other Gradle plugins, including Android and Kotlin
// ...
// Apollo Kotlin Gradle plugin
id("com.apollographql.apollo").version("LATEST_APOLLO_VERSION")
}Add the runtime dependency:
dependencies {
// Other dependencies
// ...
// Apollo runtime
implementation("com.apollographql.apollo:apollo-runtime") // Note: no need to specify version here because the plugin will manage it
}Define a service (one per GraphQL endpoint if multiple are needed).
apollo {
service("service") {
packageName.set("com.example.graphql")
}
}Map custom scalars to Kotlin types and adapters.
apollo {
service("service") {
// ...
mapScalar("GeoPoint", "com.example.graphql.GeoPoint", "com.example.graphql.GeoPointAdapter")
}
}Some commonly used scalars adapters are available in this library: https://github.com/apollographql/apollo-kotlin-adapters (opens in a new tab). Use it to avoid writing your own adapters for common types like BigDecimal, Instant. etc.
Prefer a checked-in schema file so builds are reproducible.
Configure introspection schema download:
apollo {
service("service") {
// ...
introspection {
endpointUrl.set("https://your.domain/graphql")
schemaFile.set(file("src/main/graphql/schema.graphqls"))
}
}
}This creates a task downloadServiceApolloSchemaFromIntrospection that downloads the schema and saves it to the specified location.
Run it before writing operations:
./gradlew downloadServiceApolloSchemaFromIntrospectionIf multiple modules are desirable, a few rules apply:
generateApolloMetadata.set(true).dependsOn(project(":schema"))isADependencyOf(project(":feature")), so only the used types are generated in the schema module.A typical layout for an Android or JVM module:
src/main/graphql/
GetUserQuery.graphql
schema.graphqls
extra.graphqls
src/main/kotlin/
com/example/myapp/
SomeClass.ktFor KMP:
src/commonMain/graphql/
GetUserQuery.graphql
schema.graphqls
extra.graphqls
src/commonMain/kotlin/
com/example/myapp/
SomeClass.ktApolloClient (or one per service in a multiple services case) and inject it via DI.val apolloClient = ApolloClient.Builder()
.serverUrl("https://your.domain/graphql")
.addHttpInterceptor(AuthorizationInterceptor(token))
.apply {
if (isDebugBuild) {
addHttpInterceptor(LoggingInterceptor(level = Level.BODY))
}
}
.build()