This document describes the gradle plugin for OpenAPI Generator.
This gradle plugin offers a declarative DSL via extensions (these are Gradle project extensions). These map almost fully 1:1 with the options you’d pass to the CLI or Maven plugin. The plugin maps the extensions to a task of the same name to provide a clean API. If you’re interested in the extension/task mapping concept from a high-level, you can check out Gradle’s docs.
Tasks are listed under the "OpenAPI Tools" tasks heading.
task name | description |
---|---|
openApiGenerate |
Generate code via Open API Tools Generator for Open API 2.0 or 3.x specification documents. |
openApiGenerators |
Lists generators available via Open API Generators. |
openApiMeta |
Generates a new generator to be consumed via Open API Generator. |
openApiValidate |
Validates an Open API 2.0 or 3.x specification document. |
Note
|
The plugin implements the above tasks as project extensions of the same name. If you’d like to declare
these tasks as dependencies to other tasks (using
|
All extensions can be rewritten as tasks. Where you can have only a single extension defined in your gradle file, you may have multiple tasks.
// Validating a single specification
openApiValidate {
inputSpec = "$rootDir/petstore-v3.0-invalid.yaml".toString()
}
// Define a task for validating one specification
task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.ValidateTask){
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
}
// Define a task for validating another specification
task validateBadSpec(type: org.openapitools.generator.gradle.plugin.tasks.ValidateTask){
inputSpec = "$rootDir/petstore-v3.0-invalid.yaml".toString()
}
// Define a task for batch validations
task validateSpecs(dependsOn: ['validateGoodSpec', 'validateBadSpec'])
Note
|
The tasks support Gradle Up-To-Date checking and Gradle Cache. Enable caching globally by setting Disable up-to-date checks and caching by setting the following property when using the extension: Disable caching for extension
tasks.withType(org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
outputs.upToDateWhen { false }
outputs.cacheIf { false }
} Disable up-to-date checks and caching for a custom task: Disable caching for custom task
task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.ValidateTask){
outputs.upToDateWhen { false }
outputs.cacheIf { false }
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
} |
plugins {
id "org.openapi.json-schema-generator" version "1.0.0"
}
Using legacy plugin application:
buildscript {
repositories {
mavenLocal()
maven { url "https://repo1.maven.org/maven2" }
// or, via Gradle Plugin Portal:
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-json-schema-generator-gradle-plugin:6.1.0"
}
}
apply plugin: 'org.openapi.json-schema-generator'
Key | Data Type | Default | Description |
---|---|---|---|
verbose |
Boolean |
false |
The verbosity of generation |
validateSpec |
Boolean |
true |
Whether or not we should validate the input spec before generation. Invalid specs result in an error. |
generatorName |
String |
None |
The name of the generator which will handle codegen. |
outputDir |
String |
None |
The output target directory into which code will be generated. |
inputSpec |
String |
None |
The Open API 2.0/3.x specification location. |
templateDir |
String |
None |
The template directory holding a custom template. |
auth |
String |
None |
Adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values. |
globalProperties |
Map(String,String) |
None |
Sets specified global properties. |
configFile |
String |
None |
Path to json configuration file. See OpenAPI Generator readme for structure details. |
skipOverwrite |
Boolean |
false |
Specifies if the existing files should be overwritten during the generation. |
packageName |
String |
(generator specific) |
Package for generated classes (where supported). |
apiPackage |
String |
(generator specific) |
Package for generated api classes. |
modelPackage |
String |
(generator specific) |
Package for generated model classes. |
modelNamePrefix |
String |
None |
Prefix that will be prepended to all model names. |
modelNameSuffix |
String |
None |
Suffix that will be appended to all model names. |
apiNameSuffix |
String |
None |
Suffix that will be appended to all api names. |
instantiationTypes |
Map(String,String) |
None |
Sets instantiation type mappings. |
typeMappings |
Map(String,String) |
None |
Sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: |
additionalProperties |
Map(String,Any) |
None |
Sets additional properties that can be referenced by the mustache templates. |
languageSpecificPrimitives |
List(String) |
None |
Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double. |
importMappings |
Map(String,String) |
None |
Specifies mappings between a given class and the import that should be used for that class. |
invokerPackage |
String |
None |
Root package for generated code. |
groupId |
String |
None |
GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators. |
id |
String |
None |
ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators. |
version |
String |
None |
Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators. |
library |
String |
None |
Reference the library template (sub-template) of a generator. |
gitHost |
String |
github.com |
Git user ID, e.g. gitlab.com. |
gitUserId |
String |
None |
Git user ID, e.g. openapitools. |
gitRepoId |
String |
None |
Git repo ID, e.g. openapi-json-schema-generator. |
releaseNote |
String |
'Minor update' |
Release note. |
httpUserAgent |
String |
None |
HTTP user agent, e.g. codegen_csharp_api_client. Generator default is 'OpenAPI-Generator/{packageVersion}/{language}', but may be generator-specific. |
reservedWordsMappings |
Map(String,String) |
None |
Specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. |
ignoreFileOverride |
String |
None |
Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation. |
removeOperationIdPrefix |
Boolean |
false |
Remove prefix of operationId, e.g. config_getId ⇒ getId. |
skipOperationExample |
Boolean |
false |
Skip examples defined in the operation |
apiFilesConstrainedTo |
List(String) |
None |
Defines which API-related files should be generated. This allows you to create a subset of generated files (or none at all). See Note Below. |
modelFilesConstrainedTo |
List(String) |
None |
Defines which model-related files should be generated. This allows you to create a subset of generated files (or none at all). See Note Below. |
supportingFilesConstrainedTo |
List(String) |
None |
Defines which supporting files should be generated. This allows you to create a subset of generated files (or none at all). See Note Below. |
generateModelTests |
Boolean |
true |
Defines whether or not model-related test files should be generated. |
generateModelDocumentation |
Boolean |
true |
Defines whether or not model-related documentation files should be generated. |
generateApiTests |
Boolean |
true |
Defines whether or not api-related test files should be generated. |
generateApiDocumentation |
Boolean |
true |
Defines whether or not api-related documentation files should be generated. |
withXml |
Boolean |
false |
A special-case setting which configures some generators with XML support. In some cases, this forces json OR xml, so the default here is false. |
configOptions |
Map(String,String) |
None |
A map of options specific to a generator. To see the full list of generator-specified parameters, please refer to [generators docs](https://github.com/OpenAPITools/openapi-json-schema-generator/blob/master/docs/generators.md). Note that any config options from a generator specific document may go here, and some generators may duplicate other options which are siblings to |
logToStderr |
Boolean |
false |
To write all log messages (not just errors) to STDOUT |
enablePostProcessFile |
Boolean |
false |
To enable the file post-processing hook. This enables executing an external post-processor (usually a linter program). This only enables the post-processor. To define the post-processing command, define an environment variable such as LANG_POST_PROCESS_FILE (e.g. GO_POST_PROCESS_FILE, SCALA_POST_PROCESS_FILE). Please open an issue if your target generator does not support this functionality. |
skipValidateSpec |
Boolean |
false |
To skip spec validation. When true, we will skip the default behavior of validating a spec before generation. |
generateAliasAsModel |
Boolean |
false |
To generate alias (array, list, map) as model. When false, top-level objects defined as array, list, or map will result in those definitions generated as top-level Array-of-items, List-of-items, Map-of-items definitions. When true, A model representation either containing or extending the array,list,map (depending on specific generator implementation) will be generated. |
engine |
String |
mustache |
Templating engine: "mustache" (default) or "handlebars" (beta) |
Note
|
Configuring any one of For more control over generation of individual files, configure an ignore file and refer to it via |
Note
|
When configuring openApiGenerate {
// other settings omitted
globalProperties = [
modelDocs: "false",
apis: "false"
]
} When enabling generation of only specific parts you either have to provide CSV list of what you particularly are generating or provide an empty string openApiGenerate {
// other settings omitted
globalProperties = [
apis: "",
models: "User:Pet"
]
} |
Key | Data Type | Default | Description |
---|---|---|---|
inputSpec |
String |
None |
The input specification to validate. Supports all formats supported by the Parser. |
recommend |
Boolean |
true |
Whether or not to offer recommendations related to the validated specification document. |
Key | Data Type | Default | Description |
---|---|---|---|
generatorName |
String |
None |
The human-readable generator name of the newly created template generator. |
packageName |
String |
org.openapitools.codegen |
The packageName generatorName to put the main class into. |
outputFolder |
String |
Current Directory |
Where to write the generated files |
This task exposes all options available via OpenAPI Generator CLI and the OpenAPI Generator Maven Plugin.
openApiGenerate {
generatorName = "kotlin"
inputSpec = "$rootDir/specs/petstore-v3.0.yaml".toString()
outputDir = "$buildDir/generated".toString()
apiPackage = "org.openapi.example.api"
invokerPackage = "org.openapi.example.invoker"
modelPackage = "org.openapi.example.model"
configOptions = [
dateLibrary: "java8"
]
}
The above code demonstrates configuration of global options as well as generator-specific config options.
This is an output-only listing task. There’s no need to add configuration to build.gradle.
$ ./gradlew openApiGenerators
> Task :openApiGenerators
The following generators are available:
CLIENT generators:
- ada
…
SERVER generators:
- ada-server
…
DOCUMENTATION generators:
- cwiki
…
CONFIG generators:
- apache2
OTHER generators:
…
BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
Note
|
Generator type listings in the above example have been truncated to avoid potential confusion with changing generator support. Please run the above task to list all available generators. |
openApiMeta {
generatorName = "Jim"
packageName = "us.jimschubert.example"
}
$ ./gradlew openApiMeta
> Task :openApiMeta
Wrote file to /Users/jim/my_project/pom.xml
Wrote file to /Users/jim/my_project/src/main/java/us/jimschubert/example/JimGenerator.java
Wrote file to /Users/jim/my_project/README.md
Wrote file to /Users/jim/my_project/src/main/resources/jim/api.mustache
Wrote file to /Users/jim/my_project/src/main/resources/jim/model.mustache
Wrote file to /Users/jim/my_project/src/main/resources/jim/myFile.mustache
Wrote file to /Users/jim/my_project/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
Created generator JimGenerator
BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
openApiValidate {
inputSpec = "/src/openapi-json-schema-generator/modules/openapi-json-schema-generator/src/test/resources/3_0/petstore.yaml"
recommend = true
}
$ ./gradlew openApiValidate --input=/Users/jim/projects/openapi-json-schema-generator/modules/openapi-json-schema-generator/src/test/resources/3_0/ping.yaml
> Task :openApiValidate
Validating spec /Users/jim/projects/openapi-json-schema-generator/modules/openapi-json-schema-generator/src/test/resources/3_0/ping.yaml
Spec is valid.
BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
$ ./gradlew openApiValidate
> Task :openApiValidate FAILED
Validating spec /Users/jim/projects/openapi-json-schema-generator/modules/openapi-json-schema-generator/src/test/resources/3_0/petstore.yaml
Spec is invalid.
Issues:
attribute info is missing
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':openApiValidate'.
> Validation failed.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
$ ./gradlew openApiValidate --input=/Users/jim/projects/openapi-json-schema-generator/modules/openapi-json-schema-generator/src/test/resources/3_0/petstore.yaml
If you want to perform multiple generation tasks, you’d want to create a task that inherits from the GenerateTask
.
Examples can be found in samples/local-spec/build.gradle.
You can define any number of generator tasks; the generated code does not need to be a JVM language.
task buildGoClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
generatorName = "go"
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
additionalProperties = [
packageName: "petstore"
]
outputDir = "$buildDir/go".toString()
configOptions = [
dateLibrary: "threetenp"
]
}
task buildKotlinClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
generatorName = "kotlin"
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
outputDir = "$buildDir/kotlin".toString()
apiPackage = "org.openapitools.example.api"
invokerPackage = "org.openapitools.example.invoker"
modelPackage = "org.openapitools.example.model"
configOptions = [
dateLibrary: "java8"
]
globalProperties = [
modelDocs: "false"
]
}
To execute your specs, you’d then do:
./gradlew buildGoClient buildKotlinClient
If you want to simplify the execution, you could create a new task with dependsOn
.
task codegen(dependsOn: ['buildGoClient', 'buildKotlinClient'])
Or, if you’re generating the code on compile, you can add these as a dependency to compileJava
or any other existing task.
You can also mix the default task openApiGenerate
with custom tasks:
compileJava.dependsOn buildKotlinClient, tasks.openApiGenerate
Note
|
You can run |
Android Studio may experience a Windows-specific Guava dependency conflict with openapi-json-schema-generator-gradle-plugin versions greater than 3.0.0.
As a workaround, you may force exclude conflicting Guava dependencies.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath('org.openapitools:openapi-json-schema-generator-gradle-plugin:1.0.0') {
exclude group: 'com.google.guava'
}
}
}
// …
configurations {
compile.exclude module: 'guava-jdk5'
}
// …
apply plugin: 'org.openapi.json-schema-generator'
See OpenAPITools/openapi-generator#1818 for more details.