• Stars
    star
    270
  • Rank 152,189 (Top 3 %)
  • Language
    Groovy
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Gradle plugin for OpenAPI YAML validation, code generation and API document publishing

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.32'             // Swagger Codegen V2
  swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.46'  // 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.32'             // Swagger Codegen V2
  swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.46'  // 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.32'
  // 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:

  • Put <script src="./swagger-spec.js"> in order to load a Swagger spec. The plugin exports the Swagger spec as swagger-spec.js file while generation.
  • Set spec: window.swaggerSpec in SwaggerUIBundle() parameters.
  • Set validatorUrl: null in SwaggerUIBundle() parameters in order to turn off the validator badge.

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.

Key Type Value Default value
inputFile File Swagger spec file. Mandatory
reportFile File File to write validation report. $buildDir/tmp/validateSwagger/report.yaml

It depends on the following JSON schema:

Task type GenerateSwaggerCode

The task accepts below properties.

Key Type Value Default value
language String Language to generate. Mandatory
inputFile File Swagger spec file. Mandatory
outputDir File Directory to write generated files. $buildDir/swagger-code
wipeOutputDir Boolean Wipe the outputDir before generation. true
library String Library type. None
configFile File JSON configuration file. None
templateDir File Directory containing the template. None
components List or Map Components to generate that is a list of models, apis and supportingFiles. All components
additionalProperties Map of String, String Additional properties. None
rawOptions List of Strings Raw command line options for Swagger Codegen None
configuration String or Configuration Configuration for Swagger Codegen configurations.swaggerCodegen
jvmArgs List of Strings Arguments passed to jvm None

Task type GenerateSwaggerUI

The task accepts below properties.

Key Type Value Default value
inputFile File Swagger spec file. Mandatory
outputDir File Directory to write Swagger UI files. $buildDir/swagger-ui
wipeOutputDir Boolean Wipe 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.

Key Type Value Default value
inputFile File Swagger spec file. Mandatory
outputDir File Directory to write ReDoc files. $buildDir/swagger-redoc
wipeOutputDir Boolean Wipe the outputDir before generation. true
scriptSrc String URL to ReDoc JavaScript. //rebilly.github.io/ReDoc/releases/latest/redoc.min.js
title String HTML title. ReDoc - $filename
options Map of Strings ReDoc 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 Variable Purpose
$GRADLE_PUBLISH_KEY Publish the plugin to Gradle Plugins
$GRADLE_PUBLISH_SECRET Publish the plugin to Gradle Plugins

More Repositories

1

kubelogin

kubectl plugin for Kubernetes OpenID Connect authentication (kubectl oidc-login)
Go
1,100
star
2

gradle-ssh-plugin

Gradle SSH Plugin
Groovy
310
star
3

gpup

A command to upload photos and movies to Google Photos Library using the official Google Photos Library API
Go
211
star
4

terraform-aws-nat-instance

Terraform module to provision a NAT Instance using an Auto Scaling Group and Spot Instance from $1/month
HCL
166
star
5

argocd-commenter

Notify ArgoCD Application status via Pull Request comment or GitHub Deployment API
Go
112
star
6

groovy-ssh

SSH automation tool based on Groovy DSL
Groovy
111
star
7

slack-docker

Slack/Mattermost Integration for notifying Docker events, written in Go
Go
109
star
8

kauthproxy

Local authentication proxy for Kubernetes Dashboard (kubectl auth-proxy)
Go
100
star
9

devops-kompose

[DEPRECATED] DevOps tools on Kubernetes with Helm charts
Smarty
80
star
10

datadog-actions-metrics

Send GitHub Actions metrics to Datadog for developer experience
TypeScript
58
star
11

terraform-aws-kops-alb

Terraform module for ALB, Route53 and nginx-ingress with kops on AWS
HCL
52
star
12

bntp

Lightweight New Tab Page with Bookmarks by Chrome extension
TypeScript
51
star
13

devops-compose

DevOps tools on Docker Compose
Shell
42
star
14

oauth2cli

Go package of OAuth 2.0 authorization for command line tools, which allows simple authorization flow for better UX
Go
40
star
15

kubectl-external-forward

kubectl plugin to connect to external host via Envoy Proxy in Kubernetes cluster
Go
40
star
16

gistnote

Evernote like Gist editor
JavaScript
40
star
17

wslexec

A wrapper to run Linux command inside WSL (Windows Subsystem for Linux) from native apps
Go
39
star
18

idea-fsnotifier-wsl

IntelliJ IDEA fsnotifier for WSL (Windows Subsystem for Linux)
C
36
star
19

kubernetes-dashboard-proxy

[DEPRECATED] Helm chart with OpenID Connect Proxy for Kubernetes Dashboard
Smarty
36
star
20

gradle-plugin-starter

Gradle plugin template project
Groovy
35
star
21

spock-spring-boot-example

An example of testing Spring Boot application with Spock framework
Groovy
33
star
22

kaniko-action

Build container image using Kaniko in GitHub Actions
TypeScript
27
star
23

feign-oauth2-example

Example of Spring Cloud Feign and Spring Security OAuth2
Groovy
26
star
24

typescript-actions-monorepo

Template of monorepo for GitHub Actions written in TypeScript
TypeScript
25
star
25

helm-github-pages

Publish your Kubernetes Helm Charts on GitHub Pages. DEPRECATED: please use https://github.com/helm/chart-releaser
Shell
22
star
26

ghcp

Tool to fork a repository, commit files, create a pull request and upload assets using GitHub API
Go
20
star
27

docker-build-cache-config-action

Generate effective cache parameters for docker/build-push-action in GitHub Actions
TypeScript
18
star
28

create-ecr-repository-action

Action to create Amazon ECR or ECR Public repository and put lifecycle policy
TypeScript
18
star
29

ktunnels

Kubernetes controller for port-forwarding from your machine to remote hosts via Envoy TCP proxy
Go
17
star
30

terraform-aws-kubernetes-irsa

Terraform module for IAM Roles for Service Accounts (IRSA) on self-hosted Kubernetes cluster such as kops
HCL
17
star
31

hide-comment-action

Action to hide (minimize) comments in pull request
TypeScript
16
star
32

keycloak-bulk

A bulk operation tool for the Keycloak identity manager
JavaScript
15
star
33

gradleupdate

Gradle badge service
Go
13
star
34

samba-dfree

Disk space calculator for Samba
Go
13
star
35

httpstub

Declarative YAML based HTTP stub server for integration test
Java
12
star
36

diff-action

Post diff to comment of pull request in GitHub Actions
TypeScript
12
star
37

yamlpatch

Apply JSON Patch to YAML Document preserving positions and comments
Go
11
star
38

hello-envoy

Example of Envoy TCP Proxy with dynamic filesystem configuration
Makefile
11
star
39

android-ble-button

BLE button app on Android
Kotlin
10
star
40

typescript-action

Template of TypeScript Action with Prettier, ESLint, TSConfig, Jest and automated release
TypeScript
10
star
41

appengine-scala-starter

App Engine Scala Template with Unfiltered and Scalate
Scala
10
star
42

hello-google-photos

Uploading photos using Google Photos Library API in Go
Go
10
star
43

appengine-spring-boot-starter

Spring Boot + Kotlin + App Engine Standard Environment
Kotlin
10
star
44

wait-for-workflows-action

Wait for workflow runs in GitHub Actions, for enabling status check in branch protection rule
TypeScript
9
star
45

kustomize-action

Run kustomize build in parallel in GitHub Action
TypeScript
9
star
46

gitbucket-docker

GitBucket Docker Image and Kubernetes Helm Chart
Shell
8
star
47

jira-to-slack

Slack / Mattermost Integration to notify JIRA events
Go
8
star
48

comment-action

Action to run a command and post a comment to pull request
TypeScript
8
star
49

spring-boot-kotlin-starter

Spring Boot and Kotlin starter
Kotlin
7
star
50

errto

Rewrite Go error handling code between errors, golang.org/x/xerrors and github.com/pkg/errors
Go
7
star
51

docker-manifest-create-action

Create a multi-architectures container image in GitHub Actions
TypeScript
7
star
52

gradle-starter

Hello World application with Gradle
Groovy
7
star
53

release-typescript-action

Automate release of TypeScript Action
TypeScript
7
star
54

deploy-lambda-action

Deploy code or container image to existing Lambda function in GitHub Actions
TypeScript
6
star
55

spring-cloud-api-gateway-example

Example Implementation of API Gateway Pattern using Spring Cloud Netflix
Groovy
6
star
56

awsswitch

Export the credentials variables to switch a role with MFA, interoperable with AWS CLI
Go
6
star
57

oauth2dev

Go package of OAuth 2.0 Device Authorization Grant (RFC 8628), compatible with golang.org/x/oauth2
Go
6
star
58

kubebuilder-updates

Scaffold code generated by the latest version of kubebuilder for patch upgrade
Go
5
star
59

dotfiles

Dot files of my environment
Shell
5
star
60

assign-pull-request-reviewers-action

Action to assign pull request reviewers by label
TypeScript
5
star
61

hubot-jira

A Hubot script for notifying JIRA events and creating backlogs on JIRA
CoffeeScript
4
star
62

deployment-action

Action to create GitHub Deployment to receive notifications from external deployment tool
TypeScript
4
star
63

aqua-action

[DEPRECATED] Use https://github.com/aquaproj/aqua-installer instead
TypeScript
4
star
64

kustomtree

A tool to sort Kustomize manifests into kind based directories
Go
4
star
65

send-datadog-action

General-purpose action to send custom metric or event to Datadog
TypeScript
4
star
66

twitter-feed-function

[OBSOLETE] Twitter Feed RSS on Google Cloud Functions
JavaScript
4
star
67

kind-oidc

How to set up Kubernetes OpenID Connect authentication using Kind
Shell
4
star
68

slack

Slack/Mattermost Incoming Webhooks API Client for Go
Go
4
star
69

kubectl-tree-e2e-test

E2E test of kubectl-tree to show how to test with Kind on GitHub Actions
Makefile
4
star
70

update-generated-files-action

Push commit to pull request for auto-fix in GitHub Actions
TypeScript
4
star
71

github-api-rate-limit-metrics-action

Action to send metrics of GitHub API rate limit to Datadog
TypeScript
4
star
72

goxzst

A command to make cross build, ZIP archives, SHA digests and render templates
Go
4
star
73

latest-gradle-wrapper

Latest version of Gradle Wrapper, continuously updated by CI
3
star
74

flux-continuous-deployment-demo

A demo of Continuous Deployment with Flux using the automated image update feature
Makefile
3
star
75

hubot-gitbucket

Hubot script for GitBucket notification
JavaScript
3
star
76

list-associated-pull-requests-action

List associated pull requests of a pull request in monorepo by GitHub Actions
TypeScript
3
star
77

wait-for-docker-image-action

Action to wait until Docker image is available at current Git revision
TypeScript
3
star
78

kubectl-snippets

Just snippets of kubectl
3
star
79

rename-exif

A command line tool to rename image files by Exif data
Ruby
3
star
80

typescript-k6

Write grafana/k6 in TypeScript, run in GitHub Actions and send to Datadog
TypeScript
3
star
81

renovate-merge-bot

Assist automerge of Renovate pull requests in GitHub Actions
TypeScript
3
star
82

go-renovate-config

Renovate config for Go and Kubernetes
3
star
83

taskwalls.appspot.com

ToDo Management Application
JavaScript
3
star
84

workflow-run-summary-action

Summarize workflow run for Slack notification
TypeScript
3
star
85

oauth2-github-app

Go package for authenticating with GitHub App Installation token, interoperable with golang.org/x/oauth2 package
Go
3
star
86

akoi-action

Action to install packages using https://github.com/suzuki-shunsuke/akoi
TypeScript
3
star
87

kubesnapshot

A command to take snapshots of EBS volumes owned by Kubernetes cluster, written in Go and ready on AWS Lambda or Kubernetes Cron Job
Go
3
star
88

delete-deployments-action

Clean up outdated GitHub Deployments in GitHub Actions
TypeScript
3
star
89

ssoexec

A wrapper to run third-party tools with AWS SSO
Go
3
star
90

buildx-push-action

[DEPRECATED] GitHub Action to build and push Docker image with BuildKit cache for multi-stage build
Shell
3
star
91

cronjob-runner

A command to run one-shot job from CronJob template and tail container logs in Kubernetes
Go
3
star
92

kube-aws-alb-starter

Kubernetes starter with kube-aws and Terraform
HCL
2
star
93

aggregate-deployments-action

Aggregate GitHub Deployments against commit SHA in GitHub Actions
TypeScript
2
star
94

swagger-security-example

An example project with Swagger security definitions such as OAuth2 and API key
Java
2
star
95

appengine-spring-boot-plugin

Gradle plugin for App Engine Standard and Spring Boot
Groovy
2
star
96

docker-mirror-multiarch

How to mirror a multi-architecture Docker image
2
star
97

kubebuilder-workflows

Reusable workflows for kubebuilder project
Makefile
2
star
98

ses-to-slack

Lambda function to forward mails from AWS SES to Slack/Mattermost
JavaScript
2
star
99

go-release-action

Publish Go binary into GitHub Releases
Go
2
star
100

instagit

Instant Git server providing HTTP access to local repositories
Java
2
star