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
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

Gradle plugin configuration


'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 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") {
schemaFiles.from(file("shared/graphql/schema.graphqls"))
}
}

By default, Apollo Kotlin combines all *.[graphqls|json|sdl] files in src/main/graphql/ (Android/JVM projects) or src/commonMain/graphql/ (multiplatform projects).

Combining multiple schema files

Apollo Kotlin supports a collection of client , including @nonnull, @optional, and @typePolicy. These directives enable you to extend your server's base schema with client-specific types and .

If you expand your schema in a separate file (usually named extra.graphqls), 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 *.[graphqls|json|sdl] files in src/main/graphql/ (Android/JVM projects) or src/commonMain/graphql/ (multiplatform projects).

Wiring generated sources

By default, Apollo Kotlin adds the generated sources:

  • to the main sourceSet for JVM projects
  • to commonMain for multiplatform projects
  • to all non-test 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 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 :

apollo {
createAllAndroidVariantServices(sourceFolder = ".", nameSuffix = "") {
// Configure the service here
packageName.set("...")
}
}
  • sourceFolder is where to find the GraphQL relative to "src/$sourceSetName/graphql". Pass "." to look into "src/$sourceSetName/graphql".
  • nameSuffix is the 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.

For instance, if certain operations should only exist in debug builds, your project structure could look like this:

- 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 if you have a specific backend per flavor, it could look like this:

- 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 a lot of variants and don't need to configure an Apollo Service for each, it may be simpler to declare the Services manually rather than using createAllAndroidVariantServices. 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 task
introspection {
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 GraphOS Studio, use the registry block instead:

apollo {
service("starwars") {
packageName.set("com.starwars")
// This will create a downloadStarwarsApolloSchemaFromRegistry task
registry {
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, , 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 and hashCode 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 and default values.
  • "dataClass" (Kotlin only and redundant with all other methods) generates the class as a data class. which will automatically generate toString, copy, equals and hashCode.

Here are some possible configurations:

apollo {
service("service") {
// Generates equals and hashCode
generateMethods.set(listOf("equalsHashCode"))
// Generates toString, equals, and hashcode (the default for Java)
generateMethods.set(listOf("equalsHashCode", "toString"))
// Only generates copy
generateMethods.set(listOf("copy"))
// Generates data classes (the default for Kotlin)
generateMethods.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 models
packageName.set("com.example")
// Adds the given directory as a GraphQL source root
srcDir("src/main/graphql")
// Operation files to include.
includes.add("**/*.graphql")
// Operation files to exclude.
excludes.add("**/*.graphqls")
// Explicitly set the schema
schemaFiles.from("src/main/graphql/schema.graphqls")
// Extend your schema locally with type extensions
schemaFiles.from("shared/graphql/schema.graphqls", "shared/graphql/extra.graphqls")
// What codegen to use. One of "operationBased", "responseBased"
codegenModels.set("operationBased")
// Warn if using a deprecated field
warnOnDeprecatedUsages.set(true)
// Fail on warnings
failOnWarnings.set(true)
// Map the "Date" custom scalar to the com.example.Date Kotlin type
mapScalar("Date", "com.example.Date")
// Shorthands to map scalar to builtin types and configure their adapter at build time
mapScalarToUpload("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 queries
operationOutputGenerator = 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 manifest
operationManifest.set("build/generated/persistedQueryManifest.json")
// Whether to generate Kotlin or Java models
generateKotlinModels.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 models
generateQueryDocument.set(true)
// Whether to generate the Schema class.
generateSchema.set(true)
// Name for the generated schema
generatedSchemaName.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 code
nullableFieldStyle.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 manageable
flattenModels.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 module
dependsOn(project(":schema"))
// Compute used types from a downstream module
isADependencyOf(project(":feature"))
// configure introspection schema download
introspection {
endpointUrl.set("https://your.domain/graphql/endpoint")
schemaFile.set(file("src/main/graphql/com/example/schema.graphqls"))
}
// configure registry schema download
registry {
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 set
outputDirConnection {
connectToKotlinSourceSet("test")
}
}
// Make IDEA aware of codegen and will run it during your Gradle Sync, default: false
generateSourcesDuringGradleSync.set(true)
// Link sqlite for Kotlin native projects
linkSqlite.set(true)
}
Previous
Multi Modules
Next
Queries
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company