Migrating to Apollo Kotlin 4

From version 3


Apollo Kotlin 3 was a major rewrite of Apollo in Kotlin multiplatform.

Apollo Kotlin 4 focuses on tooling, stability and making the library more maintainable, so it can evolve smoothly for the many years to come.

While most of the core APIs stayed the same, Apollo Kotlin 4 contains a few binary breaking changes. To account for that, and in order to be more future-proof, we changed the package name to com.apollographql.apollo. See the Apollo Kotlin evolution policy for more details.

Apollo Kotlin 4 removes some deprecated symbols. We strongly recommend updating to the latest 3.x release and removing deprecated usages before migrating to version 4.

Important changes are:

Read below for more details.

Automatic migration using the Android Studio/IntelliJ plugin

Apollo Kotlin 4 ships with a companion Android Studio/IntelliJ plugin that automates most of the migration.

It automates most of the API changes but cannot deal with behavior changes like error handling.

We recommend using the plugin to automate the repetitive tasks but still go through this document for the details.

Group id / plugin id / package name

Apollo Kotlin 4 uses a new identifier for its maven group id, Gradle plugin id and package name : com.apollographql.apollo.

This also allows to run versions 4 and 3 side by side if needed.

In most cases, you can update the identifier in your project by performing a find-and-replace and replacing com.apollographql.apollo3 with com.apollographql.apollo.

Group id

The maven group id used to identify Apollo Kotlin 4 artifacts is com.apollographql.apollo:

Kotlin
1// Replace:
2implementation("com.apollographql.apollo3:apollo-runtime:3.8.4")
3
4// With:
5implementation("com.apollographql.apollo:apollo-runtime:4.0.0")

Gradle plugin id

The Apollo Kotlin 4.0 Gradle plugin id is com.apollographql.apollo:

Kotlin
1// Replace:
2plugins {
3  id("com.apollographql.apollo3") version "3.8.4"
4}
5
6// With:
7plugins {
8  id("com.apollographql.apollo") version "4.0.0"
9}

Package name

Apollo Kotlin 4 classes use the com.apollographql.apollo package:

Kotlin
1// Replace:
2import com.apollographql.apollo3.ApolloClient
3import com.apollographql.apollo3.*
4
5// With:
6import com.apollographql.apollo.ApolloClient
7import com.apollographql.apollo.*

Moved artifacts

Over the years, a lot of support functionality was added alongside the apollo-api and apollo-runtime artifacts. While useful, most of this functionality doesn't share the same level of stability and maturity as the core artifacts and bundling them did not make much sense.

Moving forward, only the core artifacts remain in the apollo-kotlin repository and are released together. Other artifacts are moved to new maven coordinates and GitHub repositories.

This will allow us to iterate faster on new functionality while keeping the core smaller and more maintainable.

The artifacts with new coordinates are:

Old coordinatesNew coordinatesNew Repository
com.apollographql.apollo3:apollo-adapterscom.apollographql.adapters:apollo-adapters-coreapollographql/apollo-kotlin-adapters
com.apollographql.adapters:apollo-adapters-kotlinx-datetimeapollographql/apollo-kotlin-adapters
com.apollographql.apollo3:apollo-compose-support-incubatingcom.apollographql.compose:compose-supportapollographql/apollo-kotlin-compose-support
com.apollographql.apollo3:apollo-compose-paging-support-incubatingcom.apollographql.compose:compose-paging-supportapollographql/apollo-kotlin-compose-support
com.apollographql.apollo3:apollo-cli-incubatingcom.apollographql.cli:apollo-cliapollographql/apollo-kotlin-cli
com.apollographql.apollo3:apollo-engine-ktorcom.apollographql.ktor:apollo-engine-ktorapollographql/apollo-kotlin-ktor-support
com.apollographql.apollo3:apollo-mockservercom.apollographql.mockserver:apollo-mockserverapollographql/apollo-kotlin-mockserver
com.apollographql.apollo3:apollo-normalized-cache-incubatingcom.apollographql.cache:normalized-cache-incubatingapollographql/apollo-kotlin-normalized-cache-incubating
com.apollographql.apollo3:apollo-normalized-cache-api-incubatingcom.apollographql.cache:normalized-cache-incubatingapollographql/apollo-kotlin-normalized-cache-incubating
com.apollographql.apollo3:apollo-normalized-cache-sqlite-incubatingcom.apollographql.cache:normalized-cache-sqlite-incubatingapollographql/apollo-kotlin-normalized-cache-incubating
com.apollographql.apollo3:apollo-runtime-javacom.apollographql.java:clientapollographql/apollo-kotlin-java-support
com.apollographql.apollo3:apollo-rx2-support-javacom.apollographql.java:rx2apollographql/apollo-kotlin-java-support
com.apollographql.apollo3:apollo-rx3-support-javacom.apollographql.java:rx3apollographql/apollo-kotlin-java-support

Those new artifacts also use a new package name. You can usually guess it by removing .apollo3:

Kotlin
1// Replace 
2import com.apollographql.apollo3.mockserver.MockServer
3
4// With
5import com.apollographql.mockserver.MockServer

apollo-runtime

Fetch errors do not throw

⚠️ caution
Error handling changes are a behavior change that is not detected at compile time. Usages of execute, toFlow and watch must be updated to the new error handling or changed to their version 3 compat equivalent.See executeV3 and toFlowV3 for temporary methods to help with the migration.See nullability for a quick peek at the future of GraphQL nullability and error handling.

In Apollo Kotlin 3, fetch errors like network errors, cache misses, and parsing errors were surfaced by throwing exceptions in ApolloCall.execute() and in Flows (ApolloCall.toFlow(), ApolloCall.watch()).

This was problematic because it was a difference in how to handle GraphQL errors vs other errors. It was also easy to forget catching the exceptions. Uncaught network errors is by far the number one error reported by the Google Play SDK Index . Moreover, throwing terminates a Flow and consumers would have to handle re-collection.

In Apollo Kotlin 4, a new field ApolloResponse.exception has been added and these errors are now surfaced by returning (for execute()) or emitting (for Flows) an ApolloResponse with a non-null exception instead of throwing it.

Queries and mutations:

Kotlin
1// Replace
2try {
3  val response = client.query(MyQuery()).execute()
4  if (response.hasErrors()) {
5    // Handle GraphQL errors
6  } else {
7    // No errors
8    val data = response.data
9    // ...
10  }
11} catch (e: ApolloException) {
12  // Handle fetch errors
13}
14
15// With
16val response = client.query(MyQuery()).execute()
17if (response.data != null) {
18  // Handle (potentially partial) data
19} else {
20  // Something wrong happened
21  if (response.exception != null) {
22    // Handle fetch errors
23  } else {
24    // Handle GraphQL errors in response.errors
25  }
26}

Subscriptions:

Kotlin
1// Replace
2client.subscription(MySubscription()).toFlow().collect { response ->
3  if (response.hasErrors()) {
4    // Handle GraphQL errors
5  }
6}.catch { e ->
7  // Handle fetch errors
8}
9
10// With
11client.subscription(MySubscription()).toFlow().collect { response ->
12  val data = response.data
13  if (data != null) {
14    // Handle (potentially partial) data
15  } else {
16    // Something wrong happened
17    if (response.exception != null) {
18      // Handle fetch errors
19    } else {
20      // Handle GraphQL errors in response.errors
21    }
22  }
23}

Note that this is true for all Flows, including watchers. If you don't want to receive error responses (like cache misses), filter them out:

Kotlin
1// Replace
2apolloClient.query(query).watch()
3
4// With
5apolloClient.query(query).watch().filter { it.exception == null }

The lower level ApolloStore APIs are not changed and throw on cache misses or I/O errors.

ApolloCompositeException is not thrown

When using the cache, Apollo Kotlin 3 throws ApolloCompositeException if no response is found. For an example, a CacheFirst fetch policy throws ApolloCompositeException(cacheMissException, apolloNetworkException) if both cache and network failed.

In those cases, Apollo Kotlin 4 throws the first exception and adds the second as a suppressed exception:

Kotlin
1// Replace
2if (exception is ApolloCompositeException) {
3  val cacheMissException = exception.first
4  val networkException = exception.second
5}
6
7// With
8val cacheMissException = exception
9val networkException = exception.suppressedExceptions.firstOrNull()

For more control over the exception, use toFlow() and collect the different ApolloResponse.

emitCacheMisses(Boolean) is removed

In Apollo Kotlin 3, when using the normalized cache, you could set emitCacheMisses(Boolean) to true to emit cache misses instead of throwing.

In Apollo Kotlin 4, cache misses always emit a response with response.exception containing a CacheMissException. emitCacheMisses(Boolean) has been removed.

With the CacheFirst, NetworkFirst and CacheAndNetwork policies, cache misses and network errors are now exposed in ApolloResponse.exception.

Migration helpers

To ease the migration from Apollo Kotlin 3, drop-in helpers functions are provided that restore the version 3 behavior:

  • ApolloCall.executeV3()

  • ApolloCall.toFlowV3()

Those helper functions:

  • throw on fetch errors

  • make CacheFirst, NetworkFirst and CacheAndNetwork policies ignore fetch errors.

  • throw ApolloComposite exception if needed.

Because of the number of different options in version 3 and the complexity of error handling, these functions may not 100% match the version 3 behavior, especially in the advanced cases involving watchers. If you are in one of those cases, we strongly recommend using the version 4 functions that are easier to reason about.

Non-standard HTTP headers are not sent by default

X-APOLLO-OPERATION-NAME and X-APOLLO-OPERATION-ID are non-standard headers and are not sent by default anymore. If you used them for logging purposes or if you are using Apollo Server CSRF prevention , you can add them back using an ApolloInterceptor :

Kotlin
1val apolloClient = ApolloClient.Builder()
2    .serverUrl(mockServer.url())
3    .addInterceptor(object : ApolloInterceptor {
4      override fun <D : Operation.Data> intercept(request: ApolloRequest<D>, chain: ApolloInterceptorChain): Flow<ApolloResponse<D>> {
5        return chain.proceed(request.newBuilder()
6            .addHttpHeader("X-APOLLO-OPERATION-NAME", request.operation.name())
7            .addHttpHeader("X-APOLLO-OPERATION-ID", request.operation.id())
8            .build()
9        )
10      }
11    })
12    .build()

ApolloCall.Builder.httpHeaders is additive

In Apollo Kotlin 3, if HTTP headers were set on an ApolloCall, they would replace the ones set on ApolloClient. In Apollo Kotlin 4 they are added instead by default. To replace them, call ApolloCall.Builder.ignoreApolloClientHttpHeaders(true).

Kotlin
1// Replace
2val call = client.query(MyQuery())
3  .httpHeaders(listOf("key", "value"))
4  .execute()
5
6// With
7val call = client.query(MyQuery())
8  .httpHeaders(listOf("key", "value"))
9  .ignoreApolloClientHttpHeaders(true)
10  .execute()

HttpEngine implements Closeable

HttpEngine now implements Closeable and has its dispose method renamed to close. If you have a custom HttpEngine, you need to implement close instead of dispose.

apollo-gradle-plugin

Multi-module dependsOn

In Apollo Kotlin 3, depending on an upstream GraphQL module is done using the apolloMetadata configuration.

In Apollo Kotlin 4, this is now done using the Service.dependsOn() API. Service.dependsOn() works for multi-services repositories and, by hiding the configuration names, allows us to change the implementation in the future if needed. This is probably going to be required to accommodate Gradle project isolation .

Kotlin
1// feature1/build.gradle.kts
2
3// Replace
4dependencies {
5  // ...
6
7  // Get the generated schema types (and fragments) from the upstream schema module 
8  apolloMetadata(project(":schema"))
9
10  // You also need to declare the schema module as a regular dependency
11  implementation(project(":schema"))
12}
13
14// With
15dependencies {
16  // ...
17  
18  // You still need to declare the schema module as a regular dependency
19  implementation(project(":schema"))
20}
21
22apollo {
23  service("service") {
24    // ...
25
26    // Get the generated schema types and fragments from the upstream schema module 
27    dependsOn(project(":schema"))
28  }
29}

Auto-detection of used types

In multi-module projects, by default, all the types of an upstream module are generated because there is no way to know in advance what types are going to be used by downstream modules. For large projects this can lead to a lot of unused code and an increased build time.

To avoid this, in Apollo Kotlin 3 you could manually specify which types to generate by using alwaysGenerateTypesMatching. In Apollo Kotlin 4 you can opt in auto-detection of used types.

To enable this, add the "opposite" link of dependencies with isADependencyOf().

Kotlin
1// schema/build.gradle.kts
2
3// Replace
4apollo {
5  service("service") {
6    // ...
7    
8    // Generate all the types in the schema module
9    alwaysGenerateTypesMatching.set(listOf(".*"))
10
11    // Enable generation of metadata for use by downstream modules 
12    generateApolloMetadata.set(true)
13  }
14}
15
16// With
17apollo {
18  service("service") {
19    // ...
20
21    // Enable generation of metadata for use by downstream modules 
22    generateApolloMetadata.set(true)
23
24    // Get used types from the downstream module1
25    isADependencyOf(project(":feature1"))
26
27    // Get used types from the downstream module2
28    isADependencyOf(project(":feature2"))
29    
30    // ...
31  }
32}

If you were using apolloUsedCoordinates, you can also remove it:

Kotlin
1dependencies {
2  // Remove this 
3  apolloUsedCoordinates(project(":feature1"))
4}

All schema types are generated in the schema module

Apollo Kotlin 3 allows to generate schema types for enums or input types in any module. While very flexible, this creates a lot of complexity:

  • Duplicate types could be generated in sibling modules.

  • It's unclear what package name to use.

    • Using the downstream module package name means the qualified name of the class changes if the type is moved to another module.

    • Using the schema module package name can be surprising as it's not the one specified in the Gradle configuration.

  • Gradle has APIs to aggregate all projects in a project isolation compatible way (see gradle#22514 ). But it's not clear yet how to do this for a subset of the projects (see gradle#29037 ).

Apollo Kotlin 4 enforces generating all schema types in a single module, the schema module. This restriction simplifies the Gradle plugin and makes it easier to debug and evolve that code.

It also means that you can't publish your schema module with a subset of the types and let other modules generate their own in another repository. If you are publishing your schema module, it needs to contain all the schema types used by your consumers, either using alwaysGenerateTypesMatching.set(listOf(".*")) or manually adding them.

If that is too much of a limitation, please open an issue with your use case and we will revisit.

Apollo metadata publications are no longer created automatically

Apollo Kotlin 3 automatically creates an "apollo" publication using artifactId ${project.name}-apollo. This created dependency resolution issues in some projects (see apollo-kotlin#4350 ).

Apollo Kotlin 4 exposes a software component instead of a publication to give more control over how publications are created. In order to publish the Apollo metadata, create a MavenPublication manually:

Kotlin
1publishing {
2  publications {
3    create("apollo", MavenPublication::class.java) {
4      from(components["apollo"])
5      artifactId = "${project.name}-apollo"
6    }
7  }
8}

Custom scalars declaration

customScalarsMapping is removed and replaced with mapScalar() which makes it easier to map to built-in types and/or provide a compile type adapter for a given type:

Kotlin
1// Replace
2customScalarsMapping.set(mapOf(
3    "Date" to "kotlinx.datetime.LocalDate"
4))
5
6// With
7mapScalar("Date", "kotlinx.datetime.LocalDate")
8
9// Replace
10customScalarsMapping.put("MyLong", "kotlin.Long")
11
12// With
13mapScalarToKotlinLong("MyLong")
14

Migrating to ApolloCompilerPlugin

Apollo Kotlin 4 introduces ApolloCompilerPlugin as a way to customize code generation. ApolloCompilerPlugin replaces compiler hooks and are loaded using the ServiceLoader API. They run in a separate classloader from your Gradle build. As a result, using Service.operationIdGenerator/Service.operationOutputGenerator together with ApolloCompilerPlugin is not possible.

Service.operationIdGenerator/Service.operationOutputGenerator are deprecated and will be removed in a future release. You can migrate to ApolloCompilerPlugin using the instructions from the dedicated page and the ApolloCompilerPlugin.operationIds() method:

Kotlin
1// Replace (in your build scripts) 
2val operationOutputGenerator = object: OperationOutputGenerator {
3  override fun generate(operationDescriptorList: Collection<OperationDescriptor>): OperationOutput {
4    return operationDescriptorList.associateBy {
5      it.source.sha1()
6    }
7  }
8  override val version: String = "v1"
9}
10
11// Or, if using OperationIdGenerator, replace
12val operationIdGenerator = object: OperationIdGenerator {
13  override fun apply(operationDocument: String, operationName: String): String {
14    return operationDocument.sha1()
15  }
16
17  override val version: String = "v1"
18}
19
20// With (in your compiler plugin module) 
21class MyPlugin: ApolloCompilerPlugin {
22  override fun operationIds(descriptors: List<OperationDescriptor>): List<OperationId>? {
23    return descriptors.map {
24      OperationId(it.source.sha1(), it.name)
25    }
26  }
27}

Operation manifest file location

Since Apollo Kotlin now supports different operation manifest formats , the operationOutput.json file is generated in "build/generated/manifest/apollo/$service/operationOutput.json" instead of "build/generated/operationOutput/apollo/$service/operationOutput.json".

useSchemaPackageNameForFragments is removed

This was provided for compatibility with 2.x and is now removed. If you need specific package names for fragments, you can use a compiler plugin and ApolloCompilerPlugin.layout() instead.

apollo-compiler

"compat" codegenModels is removed

The "compat" codegen models was provided for compatibility with 2.x and is now removed. "operationBased" is more consistent and generates less code:

Kotlin
1// Replace
2apollo {
3  service("service") {
4    codegenModels.set("compat")
5  }
6}
7
8// With
9apollo {
10  service("service") {
11    codegenModels.set("operationBased")
12  }
13}

In the generated models, inline fragments accessors are prefixed with on:

Kotlin
1// Replace
2data.hero.asDroid
3
4// With
5data.hero.onDroid

The fragments synthetic property is not needed anymore:

Kotlin
1// Replace
2data.hero.fragments.heroDetails
3
4// With
5data.hero.heroDetails

Finally, some fields that were merged from inline fragments in their parents must now be accessed through the inline fragment:

Kotlin
1// Replace
2/**
3 * {
4 *   hero {
5 *     # this condition is always true
6 *     # allowing to merge the name field
7 *     ... on Character {
8 *       name
9 *     }
10 *   }
11 * }
12 */
13data.hero.name
14
15// With 
16/**
17 * name is not merged anymore
18 */
19data.hero.onCharacter?.name
 note
The Android Studio plugin provides a compat to operationBased migration tool which automates a lot of these changes.

Data builders

In Apollo Kotlin 3, using data builders with fragments required nesting the fields in a buildFoo {} block to determine the specific type returned.

In Apollo Kotlin 4, this is specified by using the first paramter of the Data() constructor function. This allows the syntax for using data builders with fragments to be the same as for operations:

Kotlin
1// Replace
2val data = AnimalDetailsImpl.Data {
3  buildCat {
4    name = "Noushka"
5    species = "Maine Coon"
6  }
7}
8
9// With
10val data = AnimalDetailsImpl.Data(Cat) {
11  name = "Noushka"
12  species = "Maine Coon"
13}

See data builders documentation for more details.

Test builders are removed

Test builders were an experimental feature that have been superseded by data builders , a simpler version that also plays nicer with custom scalars.

In Apollo Kotlin 4, test builders are no longer available - please refer to the data builders documentation for more information.

Enum class names now have their first letter capitalized

For consistency with other types, GraphQL enums are now capitalized in Kotlin. You can restore the previous behavior using @targetName:

GraphQL
1# Make sure `someEnum` isn't renamed to `SomeEnum`
2enum someEnum @targetName(name: "someEnum"){
3  A
4  B
5}

__Schema is in the schema subpackage

When using the generateSchema option, to avoid a name clash with the introspection type of the same name, the __Schema type is now generated in a schema subpackage (instead of type):

Kotlin
1// Replace
2import com.example.type.__Schema
3
4// With
5import com.example.schema.__Schema

KotlinLabs directives are now at version 0.3

The embedded kotlin_labs directives are now at version 0.3.

These are the client directives supported by Apollo Kotlin. They are imported automatically but if you relied on an explicit import for renames or another reason, you'll need to bump the version:

GraphQL
1# Replace
2extend schema @link(url: "https://specs.apollo.dev/kotlin_labs/v0.1/", import: ["@typePolicy"])
3
4# With
5extend schema @link(url: "https://specs.apollo.dev/kotlin_labs/v0.3/", import: ["@typePolicy"])

This is a backward compatible change.

Directive usages are validated

In Apollo Kotlin 4, all directive usages are validated against their definition. If you have queries using client side directives:

GraphQL
1query HeroName {
2  hero {
3    # WARNING: '@required' is not defined by the schema
4    name @required
5  }
6}

Those queries are now required to have a matching directive definition in the schema. If you downloaded your schema using introspection, this shouldn't be an issue.

In some cases, for client directives and/or if you did not use introspection, the directive definition might be missing. For those cases, you can add it explicitly in a extra.graphqls file:

GraphQL
1directive @required on FIELD

Sealed class UNKNOWN__ constructors are private

When generating enums as sealed classes with the sealedClassesForEnumsMatching option, the UNKNOWN__ constructor is now generated as private, to prevent its accidental usage.

It is recommended to update your schema instead of instantiating an UNKNOWN__ value, but if you need to, use the safeValueOf method instead:

Kotlin
1// Replace
2val myEnum = MyEnum.UNKNOWN__("foo")
3
4// With
5val myEnum = MyEnum.safeValueOf("foo")

apollo-normalized-cache

Configuration order

The normalized cache must be configured before the auto persisted queries, configuring it after will now fail (see https://github.com/apollographql/apollo-kotlin/pull/4709 ).

Kotlin
1// Replace
2val apolloClient = ApolloClient.Builder()
3  .serverUrl(...)
4  .autoPersistedQueries(...)
5  .normalizedCache(...)
6  .build()
7
8// With
9val apolloClient = ApolloClient.Builder()
10  .serverUrl(...)
11  .normalizedCache(...)
12  .autoPersistedQueries(...)
13  .build()

apollo-ast

In Apollo Kotlin 3, apollo-ast uses Antlr to parse GraphQL documents.

In Apollo Kotlin 4, apollo-ast uses its own recursive descent parser. Not only does it remove a dependency but it's also faster and supports KMP. We took this opportunity to clean the apollo-ast API:

  • The AST classes (GQLNode and subclasses) as well as Introspection classes are not data classes anymore (see https://github.com/apollographql/apollo-kotlin/pull/4704/ ).

  • The class hierarchy has been tweaked so that GQLNamed, GQLDescribed and GQLHasDirectives are more consistently inherited from.

  • GQLSelectionSet and GQLArguments are removed from GQLField and GQLInlineFragment. Use .selections directly.

  • GQLInlineFragment.typeCondition is now nullable to account for inline fragments who inherit their type condition.

  • SourceLocation.position is renamed to SourceLocation.column and is now 1-indexed.

  • GQLNode.sourceLocation is now nullable to account for the cases where the nodes are constructed programmatically.

  • File.toSchema() and String.toSchema() are removed. Instead use toGQLDocument().toSchema().

Example of a migration

If you are looking for inspiration, we updated the version 3 integration tests to use version 4 . If you have an open source project that migrated, feel free to share it, and we'll include it here.