Gradle plugin configuration
Apollo Kotlin's default configuration works for the majority of use cases. If you're getting started, see the getting started guide for an overview of the default Gradle configuration.
This article describes configuration options for advanced use cases when using Gradle.
Using multiple GraphQL APIs
Apollo Kotlin supports communicating with multiple GraphQL endpoints with different schemas. To do so, create multiple services like so:
apollo {service("starwars") {srcDir("src/main/graphql/starwars")packageName.set("com.starwars")}service("githunt") {srcDir("src/main/graphql/githunt")packageName.set("com.githunt")}}
Specifying the schema location
Specify the location of your schema file using the schemaFile
property:
apollo {service("service") {schemaFile.set(file("shared/graphql/schema.graphqls"))}}
By default, Apollo Kotlin combines all files in your project that match the pattern schema.[graphqls|json|sdl]
.
Combining multiple schema files
Apollo Kotlin supports a collection of client directives, including @nonnull
, @optional
, and @typePolicy
. These
directives enable you to extend your server's base schema with client-specific types and fields.
If you expand your schema in a separate file, you can instruct Apollo Kotlin to construct its schema from a combination of multiple files, like so:
apollo {service("service") {schemaFiles.setFrom("shared/graphql/schema.graphqls", "shared/graphql/extra.graphqls")}}
By default, Apollo Kotlin combines all files in your project that match the pattern schema.[graphqls|json|sdl]
.
Wiring generated source
By default, Apollo Kotlin adds generated source:
- to the
main
sourceSet for JVM projects - to
commonMain
for multiplatform projects - to all non-test variants for Android projects
You can customize this behavior with the outputDirConnection
property. For example, to wire a service to the test
source set of a Kotlin
JVM project:
apollo {service("service") {outputDirConnection {connectToKotlinSourceSet("test")}}}
Android variants support
It is sometimes useful to have different operations or schemas depending on the variant of your Android project.
To do this, you can instruct the Gradle plugin to automatically configure a Service per variant, like so:
apollo {createAllAndroidVariantServices(sourceFolder = ".", nameSuffix = "") {// Configure the service herepackageName.set("...")}}
sourceFolder
where to find the GraphQL relative to "src/$sourceSetName/graphql". Pass "." to look into " src/$sourceSetName/graphql".nameSuffix
a suffix to use for the service name. Leave blank to use the variant name as is.
Similarly to what the Android variant system does with source code, the GraphQL files are handled additively, and files
in src/main/graphql
are included in all services. This means your project could look like this (e.g. when certain
operations must only exist in debug builds):
- main- graphql- schema.graphqls // Schema for all variants- operations.graphql // Operations shared by all variants- debug- graphql- operations.graphql // Operations specific to the 'debug' build type
Or for instance like this (specific backend per flavor):
- main- demo- graphql- schema.graphqls // Schema for the 'demo' flavor- operations.graphql // Operations specific to the 'demo' flavor- full- graphql- schema.graphqls // Schema for the 'full' flavor- operations.graphql // Operations specific to the 'full' flavor
If you have many variants and don't need to configure an Apollo Service for each one of them, it may be simpler to declare the Services manually, for instance:
apollo {service("debug") {srcDir(file("src/debug/graphql/"))packageName.set("com.example")outputDirConnection {connectToAndroidSourceSet("debug")}}service("release") {srcDir(file("src/release/graphql/"))packageName.set("com.example")outputDirConnection {connectToAndroidSourceSet("release")}}}
Downloading a schema
By default, the Gradle plugin registers a downloadApolloSchema
task that you can use from the command line:
# --schema is interpreted relative to the project's root directory (can also be an absolute path). This example# assumes the root project directory and an Android app in `app`./gradlew downloadApolloSchema \--endpoint="https://your.domain/graphql/endpoint" \--schema="app/src/main/graphql/com/example/schema.graphqls"
If you're doing this often or want to automate the process from CI, you can configure an introspection {}
block:
apollo {service("starwars") {packageName.set("com.starwars")// This will create a downloadStarwarsApolloSchemaFromIntrospection taskintrospection {endpointUrl.set("https://your.domain/graphql/endpoint")// The path is interpreted relative to the current project here, no need to prepend 'app'schemaFile.set(file("src/main/graphql/com/example/schema.graphqls"))}}}
This will create a task
named download<ServiceName>ApolloSchemaFromIntrospection
(downloadServiceApolloSchemaFromIntrospection
by default).
If you register your schema with Apollo Studio, use the registry
block
instead:
apollo {service("starwars") {packageName.set("com.starwars")// This will create a downloadStarwarsApolloSchemaFromRegistry taskregistry {key.set(System.getenv("APOLLO_KEY"))graph.set(System.geten("APOLLO_GRAPH"))// The path is interpreted relative to the current project here, no need to prepend 'app'schemaFile.set(file("src/main/graphql/com/example/schema.graphqls"))}}}
This will create a task named download<ServiceName>ApolloSchemaFromRegistry
(downloadServiceApolloSchemaFromRegistry
by default).
With the Android Studio plugin, you can also go to Tools | Apollo | Download schema which acts as a shortcut to these tasks.
Generated methods
By default all Kotlin models, operations, fragments, and input objects are generated as data classes. This means that the Kotlin compiler will
auto-generate toString
, equals
hashCode
, copy
and componentN
for most generated classes. If you don't think you need all of those
auto-generated methods, and/or you are worried about the size of the generated code, you can configure the Apollo compiler to generate none
or a subset of the data class methods. To do this, set generateMethods
to a list of the methods you need. The available methods are:
- "equalsHashCode" generates
equals
andhashCode
methods that will compare generated class properties - "toString" generates a method that will print a pretty string representing the data in the class
- "copy" (Kotlin only) generates a method that will copy the class with named parameters for
- "dataClass" (Kotlin only and redundant with all other methods) generates the class as a data class
which will automatically generate
toString
,copy
,equals
andhashCode
.
Here are some possible configurations:
apollo {service("service") {// Generates equals/hashCodegenerateMethods.set(listOf("equalsHashCode"))// Also generates toString, equals, and hashcodegenerateMethods.set(listOf("equalsHashCode", "toString"))// Only generates copygenerateMethods.set(listOf("copy"))// Generates data classesgenerateMethods.set(listOf("dataClass"))}}
All options
Below is a summary of the Gradle options in a single code block. For more details, take a look at the ApolloExtension KDoc
apollo {service("api") {// The package name for the generated modelspackageName.set("com.example")// Adds the given directory as a GraphQL source rootsrcDir("src/main/graphql")// Operation files to include.includes.add("**/*.graphql")// Operation files to exclude.excludes.add("**/*.graphqls")// explicitly set the schemaschemaFile.set("src/main/graphql/schema.graphqls")// you can also merge different files togetherschemaFile.setFrom("shared/graphql/schema.graphqls", "shared/graphql/extra.graphqls")// What codegen to use. One of "operationBased", "responseBased"codegenModels.set("operationBased")// Warn if using a deprecated fieldwarnOnDeprecatedUsages.set(true)// Fail on warningsfailOnWarnings.set(true)// Map the "Date" custom scalar to the com.example.Date Kotlin typemapScalar("Date", "com.example.Date")// Shorthands to map scalar to builtin types and configure their adapter at build timemapScalarToUpload("Upload")mapScalarToKotlinString("MyString")mapScalarToKotlinInt("MyInt")mapScalarToKotlinDouble("MyDouble")mapScalarToKotlinFloat("MyFloat")mapScalarToKotlinLong("MyLong")mapScalarToKotlinBoolean("MyBoolean")mapScalarToKotlinAny("MyAny")mapScalarToJavaString("MyString")mapScalarToJavaInteger("MyInteger")mapScalarToJavaDouble("MyDouble")mapScalarToJavaFloat("MyFloat")mapScalarToJavaLong("MyLong")mapScalarToJavaBoolean("MyBoolean")mapScalarToJavaObject("MyObject")// Configure operation ids for persisted queriesoperationOutputGenerator = object : OperationOutputGenerator {override fun generate(operationDescriptorList: Collection<OperationDescriptor>): OperationOutput {return operationDescriptorList.map {it.source.sha256() to it}.toMap()}override val version = "v1"}// The format to output for the operation manifest.operationManifestFormat.set("persistedQueryManifest")// The file where to write the operaiton manifestoperationManifest.set("build/generated/persistedQueryManifest.json")// Whether to generate Kotlin or Java modelsgenerateKotlinModels.set(true)// Target language version for the generated code.languageVersion.set("1.5")// Whether to suffix operation name with 'Query', 'Mutation' or 'Subscription'useSemanticNaming.set(true)// Whether to generate kotlin constructors with `@JvmOverloads` for more graceful Java interop experience when default values are present.addJvmOverloads.set(true)// Whether to generate Kotlin models with `internal` visibility modifier.generateAsInternal.set(true)// Whether to generate default implementation classes for GraphQL fragments.generateFragmentImplementations.set(true)// Whether to write the query document in modelsgenerateQueryDocument.set(true)// Whether to generate the Schema class.generateSchema.set(true)// Name for the generated schemageneratedSchemaName.set("Schema")// Whether to generate operation variables as [com.apollographql.apollo3.api.Optional]generateOptionalOperationVariables.set(true)// Whether to generate the type safe Data builders.generateDataBuilders.set(true)// Whether to generate response model builders for Java.generateModelBuilders.set(true)// Which methods to auto generate (can include: `equalsHashCode`, `copy`, `toString`, or `dataClass`)generateMethods.set(listOf("dataClass"))// Whether to generate fields as primitive types (`int`, `double`, `boolean`) instead of their boxed types (`Integer`, `Double`, etc..)generatePrimitiveTypes.set(true)// Opt-in Builders for Operations, Fragments and Input types. Builders are more ergonomic than default arguments when there are a lot of// optional arguments.generateInputBuilders.set(true)// The style to use for fields that are nullable in the Java generated codenullableFieldStyle.set("apolloOptional")// Whether to decapitalize field names in the generated models (for instance `FooBar` -> `fooBar`)decapitalizeFields.set(false)// Whether to add the [JsExport] annotation to generated models.jsExport.set(true)// When to add __typename.addTypename.set("always")// Whether to flatten the models. File paths are limited on MacOSX to 256 chars and flattening can help keeping the path length manageableflattenModels.set(true)// A list of [Regex] patterns for GraphQL enums that should be generated as Kotlin sealed classes instead of the default Kotlin enums.sealedClassesForEnumsMatching.set(listOf(".*"))// A list of [Regex] patterns for GraphQL enums that should be generated as Java classes.classesForEnumsMatching.set(listOf(".*"))// Whether fields with different shape are disallowed to be merged in disjoint types.fieldsOnDisjointTypesMustMerge.set(false)// The directory where the generated models will be written.outputDir.set("build/generated/apollo")// Whether to generate Apollo metadata. Apollo metadata is used for multi-module support.generateApolloMetadata.set(true)// list of [Regex] patterns matching for types and fields that should be generated whether they are used by queries/fragments in this module or not.alwaysGenerateTypesMatching.set(listOf(".*"))// Reuse the schema from an upstream moduledependsOn(project(":schema"))// Compute used types from a downstream moduleisADependencyOf(project(":feature"))// configure introspection schema downloadintrospection {endpointUrl.set("https://your.domain/graphql/endpoint")schemaFile.set(file("src/main/graphql/com/example/schema.graphqls"))}// configure registry schema downloadregistry {key.set(System.getenv("APOLLO_KEY"))graph.set(System.geten("APOLLO_GRAPH"))schemaFile.set(file("src/main/graphql/com/example/schema.graphqls"))}// wire the generated models to the "test" source setoutputDirConnection {connectToKotlinSourceSet("test")}}// Make IDEA aware of codegen and will run it during your Gradle Sync, default: falsegenerateSourcesDuringGradleSync.set(true)// Link sqlite for Kotlin native projectslinkSqlite.set(true)}