Home

Awesome

Gradle Swagger Generator Plugin build Gradle Status

Table of content

Introduction

This is a Gradle plugin for the following tasks:

See also the following examples:

Code Generation

Create a project with the following build script.

plugins {
  id 'org.hidetake.swagger.generator' version '2.19.2'
}

repositories {
  mavenCentral()
}

dependencies {
  swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.34'             // Swagger Codegen V2
  swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.47'  // or Swagger Codegen V3
  swaggerCodegen 'org.openapitools:openapi-generator-cli:3.3.4'     // or OpenAPI Generator
}

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
    }
  }
}

The task generates source code into build/swagger-code-petstore.

% ./gradlew generateSwaggerCode
:resolveSwaggerTemplate NO-SOURCE
:generateSwaggerCodePetstore
:generateSwaggerCode NO-SOURCE

Document Generation

Swagger UI

Create a project with the following build script.

plugins {
  id 'org.hidetake.swagger.generator' version '2.19.2'
}

repositories {
  mavenCentral()
}

dependencies {
  swaggerUI 'org.webjars:swagger-ui:3.52.5'
}

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
  }
}

The task generates an API document as build/swagger-ui-petstore.

% ./gradlew generateSwaggerUI
:generateSwaggerUIPetstore
:generateSwaggerUI NO-SOURCE

ReDoc

Create a project with the following build script.

plugins {
  id 'org.hidetake.swagger.generator' version '2.19.2'
}

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
  }
}

The task generates an API document as build/redoc-petstore.

% ./gradlew generateReDoc
:generateReDocPetstore
:generateReDoc NO-SOURCE

HTML

Create a project with the following build script.

plugins {
  id 'org.hidetake.swagger.generator' version '2.19.2'
}

repositories {
  mavenCentral()
}

dependencies {
  swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.34'             // Swagger Codegen V2
  swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.47'  // or Swagger Codegen V3
}

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'html'  // html or html2
    }
  }
}

The task generates a static HTML into build/swagger-code-petstore.

% ./gradlew generateSwaggerCode
:resolveSwaggerTemplate NO-SOURCE
:generateSwaggerCodePetstore
:generateSwaggerCode NO-SOURCE

Recipes

See the example projects in acceptance-test.

Use configuration file

We can use a JSON configuration file as follows:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
      configFile = file('config.json')
    }
  }
}

config.json depends on the language and framework. For example,

{
  "library": "spring-mvc",
  "modelPackage": "example.model",
  "apiPackage": "example.api",
  "invokerPackage": "example"
}

Run the task with Help postfix to show available JSON configuration.

% ./gradlew generateSwaggerCodePetstoreHelp
:generateSwaggerCodePetstoreHelp
=== Available raw options
NAME
        swagger-codegen-cli generate - Generate code with chosen lang

SYNOPSIS
        swagger-codegen-cli generate
                [(-a <authorization> | --auth <authorization>)]
...

=== Available JSON configuration for language spring:

CONFIG OPTIONS
	sortParamsByRequiredFlag
...

Build generated code

It is recommended to generate code into an ephemeral directory (e.g. build) and exclude it from a Git repository. We can compile generated code as follows:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
      configFile = file('config.json')
    }
  }
}

// Configure compile task dependency and source
compileJava.dependsOn swaggerSources.petstore.code
sourceSets.main.java.srcDir "${swaggerSources.petstore.code.outputDir}/src/main/java"
sourceSets.main.resources.srcDir "${swaggerSources.petstore.code.outputDir}/src/main/resources"

See also the following examples:

Validate YAML before code generation

It is recommended to validate an OpenAPI YAML before code generation in order to avoid invalid code generated.

If you use OpenAPI Generator as generator, YAML validation is embeding.

We can validate a YAML as follows:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
      configFile = file('config.json')
      // Validate YAML before code generation. for Swagger Codegen V2 / V3
      dependsOn validation
    }
  }
}

Selective generation

We can control output of code generation. At default everything is generated but only models and APIs are generated in the following:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
      configFile = file('config.json')
      // Generate only models and controllers
      components = ['models', 'apis']
    }
  }
}

components property accepts a list of strings or map.

// generates only models
components = ['models']
components = [models: true]

// generate only User and Pet models
components = [models: ['User', 'Pet']]
components = [models: 'User,Pet']

// generate only APIs (without tests)
components = [apis: true, apiTests: false]
components = [apis: true, apiTests: null]

See selective generation section for details.

Use custom template

We can use a custom template for the code generation as follows:

// build.gradle
swaggerSources {
  inputFile = file('petstore.yaml')
  petstore {
    language = 'spring'
    // Path to the template directory
    templateDir = file('templates/spring-mvc')
  }
}

See also the following examples:

Use custom generator class

We can use a custom generator class for the code generation as follows:

// build.gradle
swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      // FQCN of the custom generator class
      language = 'CustomGenerator'
    }
  }
}

dependencies {
  swaggerCodegen project('generators')
}

swaggerSources*.code*.dependsOn 'generators:jar'
// generators/build.gradle (child project)
dependencies {
  implementation 'io.swagger:swagger-codegen-cli:2.4.24'
}
// generators/src/main/groovy/CustomGenerator.groovy
import io.swagger.codegen.languages.SpringCodegen

class CustomGenerator extends SpringCodegen {
}

See also the following examples:

Externalize template or generator class

In some large use case, we can release a template or generator to an external repository and use them from projects.

// build.gradle
repositories {
  // Use external repository for the template and the generator class
  maven {
    url 'https://example.com/nexus-or-artifactory'
  }
  mavenCentral()
}

dependencies {
  swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.34'
  // Add dependency for the template
  swaggerTemplate 'com.example:swagger-templates:1.0.0'
  // Add dependency for the generator class
  swaggerCodegen 'com.example:swagger-generators:1.0.0'
}

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'spring'
      // The plugin automatically extracts template JAR into below destination
      templateDir = file("${resolveSwaggerTemplate.destinationDir}/spring-mvc")
    }
  }
}

See also the following examples:

Use multiple sources

We can handle multiple sources in a project as follows:

// build.gradle
swaggerSources {
    petstoreV1 {
        inputFile = file('v1-petstore.yaml')
        code {
            language = 'spring'
            configFile = file('v1-config.json')
        }
    }
    petstoreV2 {
        inputFile = file('v2-petstore.yaml')
        code {
            language = 'spring'
            configFile = file('v2-config.json')
        }
    }
}

compileJava.dependsOn swaggerSources.petstoreV1.code, swaggerSources.petstoreV2.code
sourceSets.main.java.srcDirs "${swaggerSources.petstoreV1.code.outputDir}/src/main/java", "${swaggerSources.petstoreV2.code.outputDir}/src/main/java"
sourceSets.main.resources.srcDirs "${swaggerSources.petstoreV1.code.outputDir}/src/main/resources", "${swaggerSources.petstoreV2.code.outputDir}/src/main/resources"

See also the following examples:

Switch version of Swagger Codegen

We can use multiple versions of Swagger Codegen as follows:

// build.gradle
configurations {
    swaggerCodegenV2
    swaggerCodegenV3
}

dependencies {
    swaggerCodegenV2 'io.swagger:swagger-codegen-cli:2.4.24'
    swaggerCodegenV3 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.30'
}

swaggerSources {
    petstoreV2 {
        inputFile = file('v2-petstore.yaml')
        code {
            language = 'spring'
            configuration = configurations.swaggerCodegenV2
        }
    }
    petstoreV3 {
        inputFile = file('v3-petstore.yaml')
        code {
            language = 'spring'
            configuration = configurations.swaggerCodegenV3
        }
    }
}

See also the following examples:

Configure Swagger UI

We can configure Swagger UI by overwriting the default index.html as follows:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    ui {
      doLast {
        copy {
          from 'index.html'
          into outputDir
        }
      }
    }
  }
}

You can create an index.html from the Swagger UI official one. It must satisfy the followings:

See also the following examples:

Compatibility

Swagger Codegen v3 and Java 16+

To use Swagger Codegen v3 on Java 16 or later, you need to set jvmArgs as follows:

swaggerSources {
  petstore {
    inputFile = file('petstore.yaml')
    code {
      language = 'html'
      jvmArgs = ['--add-opens=java.base/java.util=ALL-UNNAMED'] // for Swagger Codegen v3 on Java 16+
    }
  }
}

See #221 for details.

Settings

The plugin adds validateSwagger, generateSwaggerCode, generateSwaggerUI and GenerateReDoc tasks. A task will be skipped if no input file is given.

Task type ValidateSwagger

The task accepts below properties.

KeyTypeValueDefault value
inputFileFileSwagger spec file.Mandatory
reportFileFileFile to write validation report.$buildDir/tmp/validateSwagger/report.yaml

It depends on the following JSON schema:

Task type GenerateSwaggerCode

The task accepts below properties.

KeyTypeValueDefault value
languageStringLanguage to generate.Mandatory
inputFileFileSwagger spec file.Mandatory
outputDirFileDirectory to write generated files.$buildDir/swagger-code
wipeOutputDirBooleanWipe the outputDir before generation.true
libraryStringLibrary type.None
configFileFileJSON configuration file.None
templateDirFileDirectory containing the template.None
componentsList or MapComponents to generate that is a list of models, apis and supportingFiles.All components
additionalPropertiesMap of String, StringAdditional properties.None
rawOptionsList of StringsRaw command line options for Swagger CodegenNone
configurationString or ConfigurationConfiguration for Swagger Codegenconfigurations.swaggerCodegen
jvmArgsList of StringsArguments passed to jvmNone

Task type GenerateSwaggerUI

The task accepts below properties.

KeyTypeValueDefault value
inputFileFileSwagger spec file.Mandatory
outputDirFileDirectory to write Swagger UI files.$buildDir/swagger-ui
wipeOutputDirBooleanWipe the outputDir before generation.true

Note that options and header are no longer supported since 2.10.0. See the Migration Guide for details.

Task type GenerateReDoc

The task accepts below properties.

KeyTypeValueDefault value
inputFileFileSwagger spec file.Mandatory
outputDirFileDirectory to write ReDoc files.$buildDir/swagger-redoc
wipeOutputDirBooleanWipe the outputDir before generation.true
scriptSrcStringURL to ReDoc JavaScript.//rebilly.github.io/ReDoc/releases/latest/redoc.min.js
titleStringHTML title.ReDoc - $filename
optionsMap of StringsReDoc tag attributes.Empty map

Contributions

This is an open source software licensed under the Apache License Version 2.0. Feel free to open issues or pull requests.

CI requires the following variables.

Environment VariablePurpose
$GRADLE_PUBLISH_KEYPublish the plugin to Gradle Plugins
$GRADLE_PUBLISH_SECRETPublish the plugin to Gradle Plugins