Skip to main content
Version: 7.x.x

Gradle Plugin Tasks

GraphQL Kotlin Gradle Plugin provides functionality to generate a lightweight GraphQL HTTP client and generate GraphQL schema directly from your source code.

info

This plugin is dependent on Kotlin compiler plugin as it generates Kotlin source code that needs to be compiled.

Usage

graphql-kotlin-gradle-plugin is published on Gradle Plugin Portal. In order to execute any of the provided tasks you need to first apply the plugin on your project.

Using plugins DSL syntax

plugins {
id("com.expediagroup.graphql") version $graphQLKotlinVersion
}

Or by using legacy plugin application

buildscript {
repositories {
maven {
url = uri("https://plugins.gradle.org/m2/")
}
}
dependencies {
classpath("com.expediagroup:graphql-kotlin-gradle-plugin:$graphQLKotlinVersion")
}
}

apply(plugin = "com.expediagroup.graphql")

Extension

GraphQL Kotlin Gradle Plugin uses an extension on the project named graphql of type GraphQLPluginExtension. This extension can be used to configure global options instead of explicitly configuring individual tasks. Once extension is configured, it will automatically download SDL/run introspection to generate GraphQL schema and subsequently generate all GraphQL clients. GraphQL Extension should be used by default, except for cases where you need to only run individual tasks.

// build.gradle.kts
import com.expediagroup.graphql.plugin.gradle.config.GraphQLScalar
import com.expediagroup.graphql.plugin.gradle.config.GraphQLSerializer
import com.expediagroup.graphql.plugin.gradle.graphql

graphql {
client {
// Boolean flag indicating whether or not selection of deprecated fields is allowed.
allowDeprecatedFields = false
// List of custom GraphQL scalar to converter mapping containing information about corresponding Java type and converter that should be used to serialize/deserialize values.
customScalars = listOf(GraphQLScalar("UUID", "java.util.UUID", "com.example.UUIDScalarConverter"))
// GraphQL server endpoint that will be used to for running introspection queries. Alternatively you can download schema directly from `sdlEndpoint` or specify local `schemaFile`.
endpoint = "http://localhost:8080/graphql"
// Optional HTTP headers to be specified on an introspection query or SDL request.
headers = mapOf("X-Custom-Header" to "Custom-Header-Value")
// Target package name to be used for generated classes.
packageName = "com.example.generated"
// Custom directory containing query files, defaults to src/main/resources
queryFileDirectory = "${project.projectDir}/src/main/resources/queries"
// Optional list of query files to be processed, takes precedence over queryFileDirectory
queryFiles = listOf(file("${project.projectDir}/src/main/resources/queries/MyQuery.graphql"))
// GraphQL schema file. Can be used instead of `endpoint` or `sdlEndpoint`.
schemaFile = file("${project.projectDir}/src/main/resources/myLocalSchema.graphql")
// GraphQL server SDL endpoint that will be used to download schema. Alternatively you can run introspection query against `endpoint` or specify local `schemaFile`.
sdlEndpoint = "http://localhost:8080/sdl"
// JSON serializer that will be used to generate the data classes.
serializer = GraphQLSerializer.JACKSON
// Timeout configuration for introspection query/downloading SDL
timeout {
// Connect timeout in milliseconds
connect = 5_000
// Read timeout in milliseconds
read = 15_000
}
// Override options that GraphQL Java uses when parsing GraphQL queries and schema definition language documents.
parserOptions {
// Override the maximum number of tokens read to prevent processing extremely large queries.
maxTokens = 15000
// Override the maximum number of whitespace tokens read to prevent processing extremely large queries.
maxWhitespaceTokens = 200000
// Modify the maximum number of characters in a document to prevent malicious documents consuming CPU
maxCharacters = 1048576
// Modify the maximum grammar rule depth to negate malicious documents that can cause stack overflows
maxRuleDepth = 500
// Single-line comments do not have any semantic meaning in GraphQL source documents and can be ignored
captureLineComments = false
// Memory usage is significantly reduced by not capturing ignored characters, especially in SDL parsing.
captureIgnoredChars = false
// Memory usage is reduced by not setting SourceLocations on AST nodes, especially in SDL parsing.
captureSourceLocation = true
}
// Opt-in flag to wrap nullable arguments in OptionalInput that distinguish between null and undefined value.
useOptionalInputWrapper = false
}
graalVm {
// List of supported packages that can contain GraphQL schema type definitions
packages = listOf("com.example")
// Application main class name
mainClassName = "com.example.ApplicationKt"
}
schema {
// List of supported packages that can contain GraphQL schema type definitions
packages = listOf("com.example")
}
}

Tasks

By default, graphql-kotlin-gradle-plugin lazily registers all its tasks which means that while they are known to the build, they are not created nor executed until something in the build needs the instantiated object (e.g. adding explicit dependency on those tasks or explicitly creating them). Configuring plugin through the graphql extension will automatically create all the corresponding tasks.

All graphql-kotlin-gradle-plugin tasks are grouped together under GraphQL task group and their names are prefixed with graphql. You can find detailed information about GraphQL kotlin tasks by running gradle help --task <taskName>.

$ gradle tasks --group graphql

GraphQL tasks
-------------
graphqlDownloadSDL - Download schema in SDL format from target endpoint.
graphqlGenerateClient - Generate HTTP client from the specified GraphQL queries.
graphqlGenerateSDL - Generate GraphQL schema in SDL format.
graphqlGenerateTestClient - Generate HTTP test client from the specified GraphQL queries.
graphqLGraalVmMetadata - Generate GraalVM reflect metadata for GraphQL Kotlin servers.
graphqlIntrospectSchema - Run introspection query against target GraphQL endpoint and save schema locally.--&gt;

graphqlDownloadSDL

Task that attempts to download GraphQL schema in SDL format from the specified endpoint and saves the underlying schema file as schema.graphql under build directory. In general, this task provides limited functionality by itself and could be used as an alternative to graphqlIntrospectSchema to generate input for the subsequent graphqlGenerateClient task.

info

This task will always be UP-TO-DATE and in order to trigger the re-download of an SDL you need to force rerun it by specifying --rerun-tasks option or by executing clean task.

Properties

PropertyTypeRequiredDescription
endpointStringyesTarget GraphQL server SDL endpoint that will be used to download schema.
Command line property is: endpoint.
headersMap<String, Any>Optional HTTP headers to be specified on a SDL request.
outputFileFileTarget GraphQL schema file to be generated.
Default value is: ${project.buildDir}/schema.graphql
timeoutConfigTimeoutConfigTimeout configuration (in milliseconds) to download schema from SDL endpoint before we cancel the request.
Default value are:
connect timeout = 5_000
read timeout = 15_000.

graphqlGenerateClient

Task that generates GraphQL Kotlin client and corresponding data classes based on the provided GraphQL queries that are evaluated against target Graphql schema. Individual clients with their specific data models are generated for each query file and are placed under specified packageName. When this task is added to the project, either through explicit configuration or through the graphql extension, it will automatically configure itself as a dependency of a compileKotlin task and resulting generated code will be automatically added to the project main source set.

Properties

PropertyTypeRequiredDescription
allowDeprecatedFieldsBooleanBoolean flag indicating whether selection of deprecated fields is allowed or not.
Default value is: false.
Command line property is: allowDeprecatedFields.
customScalarsList<GraphQLScalar>List of custom GraphQL scalar to converter mappings containing information about corresponding Java type and converter that should be used to serialize/deserialize values.
packageNameStringyesTarget package name for generated code.
Command line property is: packageName.
parserOptionsGraphQLParserOptionsConfigures the settings used when parsing GraphQL queries and schema definition language documents.
queryFilesFileCollectionList of query files to be processed. Instead of a list of files to be processed you can specify queryFileDirectory directory instead. If this property is specified it will take precedence over the corresponding directory property.
queryFileDirectoryDirectoryDirectory file containing GraphQL queries. Instead of specifying a directory you can also specify list of query file by using queryFiles property instead.
Default value is: src/main/resources.
schemaFileFileyesGraphQL schema file that will be used to generate client code.
serializerGraphQLSerializerJSON serializer that will be used to generate the data classes.
Default value is: GraphQLSerializer.JACKSON.
useOptionalInputWrapperBooleanBoolean opt-in flag to wrap nullable arguments in OptionalInput that distinguish between null and undefined/omitted value.
Default value is: false.
Command line property is: useOptionalInputWrapper

By default, this task will generate Jackson compatible data models. See client serialization documentation for details on how to update this process to use kotlinx.serialization instead.

Parameter Details

  • parserOptions - Configure options for parsing GraphQL queries and schema definition language documents. Settings here override the defaults set by GraphQL Java.
  // Override options that GraphQL Java uses when parsing GraphQL queries and schema definition language documents.
parserOptions {
// Override the maximum number of tokens read to prevent processing extremely large queries.
maxTokens = 15000
// Override the maximum number of whitespace tokens read to prevent processing extremely large queries.
maxWhitespaceTokens = 200000
// Modify the maximum number of characters in a document to prevent malicious documents consuming CPU
maxCharacters = 1048576
// Modify the maximum grammar rule depth to negate malicious documents that can cause stack overflows
maxRuleDepth = 500
// Memory usage is significantly reduced by not capturing ignored characters, especially in SDL parsing.
captureIgnoredChars = false
// Memory usage is reduced by not setting SourceLocations on AST nodes, especially in SDL parsing.
captureSourceLocation = true
// Single-line comments do not have any semantic meaning in GraphQL source documents and can be ignored
captureLineComments = true
}

graphqlGenerateSDL

Task that generates GraphQL schema in SDL format from your source code using reflections. Utilizes graphql-kotlin-schema-generator to generate the schema from classes implementing graphql-kotlin-server marker Query, Mutation and Subscription interfaces. In order to limit the amount of packages to scan, this task requires users to provide a list of packages that can contain GraphQL types.

Properties

PropertyTypeRequiredDescription
packagesList<String>yesList of supported packages that can be scanned to generate SDL.
schemaFileFileTarget GraphQL schema file to be generated.
Default value is: ${project.buildDir}/schema.graphql

By default, this task will attempt to generate the schema using NoopSchemaGeneratorHooks. If you need to customize your schema generation process, you will need to provide your custom instance of SchemaGeneratorHooksProvider service provider. Service provider can be provided as part of your project, included in one of your project dependencies or through explicitly provided artifact to the graphqlSDL configuration.

dependencies {
graphqlSDL("com.expediagroup:graphql-kotlin-federated-hooks-provider:$graphQLKotlinVersion")
}

graphqlGenerateTestClient

Task that generates GraphQL Kotlin test client and corresponding data classes based on the provided GraphQL queries that are evaluated against target Graphql schema. Individual test clients with their specific data models are generated for each query file and are placed under specified packageName. When this task is added to the project it will automatically configure itself as a dependency of a compileTestKotlin task and resulting generated code will be automatically added to the project test source set.

Properties

PropertyTypeRequiredDescription
allowDeprecatedFieldsBooleanBoolean flag indicating whether selection of deprecated fields is allowed or not.
Default value is: false.
Command line property is: allowDeprecatedFields.
customScalarsList<GraphQLScalar>List of custom GraphQL scalar to converter mappings containing information about corresponding Java type and converter that should be used to serialize/deserialize values.
packageNameStringyesTarget package name for generated code.
Command line property is: packageName.
parserOptionsGraphQLParserOptionsConfigures the settings used when parsing GraphQL queries and schema definition language documents.
queryFilesFileCollectionList of query files to be processed. Instead of a list of files to be processed you can specify queryFileDirectory directory instead. If this property is specified it will take precedence over the corresponding directory property.
queryFileDirectoryDirectoryDirectory file containing GraphQL queries. Instead of specifying a directory you can also specify list of query file by using queryFiles property instead.
Default value is: src/test/resources.
schemaFileFileyesGraphQL schema file that will be used to generate client code.
serializerGraphQLSerializerJSON serializer that will be used to generate the data classes.
Default value is: GraphQLSerializer.JACKSON.
useOptionalInputWrapperBooleanBoolean opt-in flag to wrap nullable arguments in OptionalInput that distinguish between null and undefined/omitted value.
Default value is: false.
Command line property is: useOptionalInputWrapper

By default, this task will generate Jackson compatible data models. See client serialization documentation for details on how to update this process to use kotlinx.serialization instead.

Parameter Details

  • parserOptions - Configure options for parsing GraphQL queries and schema definition language documents. Settings here override the defaults set by GraphQL Java.
  // Override options that GraphQL Java uses when parsing GraphQL queries and schema definition language documents.
parserOptions {
// Override the maximum number of tokens read to prevent processing extremely large queries.
maxTokens = 15000
// Override the maximum number of whitespace tokens read to prevent processing extremely large queries.
maxWhitespaceTokens = 200000
// Modify the maximum number of characters in a document to prevent malicious documents consuming CPU
maxCharacters = 1048576
// Modify the maximum grammar rule depth to negate malicious documents that can cause stack overflows
maxRuleDepth = 500
// Memory usage is significantly reduced by not capturing ignored characters, especially in SDL parsing.
captureIgnoredChars = false
// Memory usage is reduced by not setting SourceLocations on AST nodes, especially in SDL parsing.
captureSourceLocation = true
// Single-line comments do not have any semantic meaning in GraphQL source documents and can be ignored
captureLineComments = true
}

graphqLGraalVmMetadata

Task that generates GraalVM Reachability Metadata for graphql-kotlin servers. Based on the GraphQL schema it will generate native-image.properties, reflect-config.json and resource-config.json metadata files under build/generated/graphqlGraalVmResources/META-INF/native-image/<groupId>/<projectName>/graphql

Task will be automatically applied if the project applies GraalVM Native Plugin.

Properties

PropertyTypeRequiredDescription
packagesList<String>yesList of supported packages that can be can contain GraphQL schema.
mainClassNameStringApplication main class name.

graphqlIntrospectSchema

Task that executes GraphQL introspection query against specified endpoint and saves the underlying schema file as schema.graphql under build directory. In general, this task provides limited functionality by itself and instead should be used to generate input for the subsequent graphqlGenerateClient task.

info

This task will always be UP-TO-DATE and in order to trigger the re-running of the introspection query you need to force rerun it by specifying --rerun-tasks option or by executing clean task.

Properties

PropertyTypeRequiredDescription
endpointStringyesTarget GraphQL server endpoint that will be used to execute introspection queries.
Command line property is: endpoint.
headersMap<String, Any>Optional HTTP headers to be specified on an introspection query.
outputFileFileTarget GraphQL schema file to be generated.
Default value is: ${project.buildDir}/schema.graphql
streamResponseBooleanBoolean property to indicate whether to use streamed (chunked) responses.
Default value is: true.
timeoutConfigTimeoutConfigTimeout configuration (in milliseconds) to download schema from SDL endpoint before we cancel the request.
Default value are:
connect timeout = 5_000
read timeout = 15_000.