How to create swagger.json using gradle?

I want to use swagger-codegen to generate REST clients and possibly static HTML documentation.

However, swagger-codegen requires swagger.json for input.

I know that I can get this from a running REST server equipped with Swagger.

But is there any way to get swagger.json directly from my Java code - i.e. generate it using gradle from source code - without having to run the application in a web container and specifying curl or a browser for it?

+8
java swagger swagger-codegen
source share
2 answers

This is a bit outdated, but I was interested in exactly the same thing ... In short, I started the study with:

  • Spring example A boot application that displays a minimal REST API;
  • Swagger API annotations
  • Springfox
  • Gradle as a build tool;

I managed to create the JSON specification as an assembly artifact using two different approaches:

I have summarized my research in a simple project located here . See Automation Section. Code and examples are included.

+2
source share

The basic idea is to add swagger-maven-plugin and your java classes in the classpath for buildScript so that you can use them in gradle, something like this:

 buildscript { repositories { mavenCentral() } dependencies { classpath files(project(':swagger-maven-example').configurations['runtime'].files) classpath files(project(':swagger-maven-example').sourceSets['main'].output.classesDir) } } 

where the first line in the dependencies gets swagger libs from the subproject, and the second line gets your classes, which should contain swagger annotations.

After that, you can call the maven plugin in gradle as a simple java class:

 // a trick to have all needed classes in the classpath def customClass = new GroovyClassLoader() buildscript.configurations.classpath.each { // println it.toURI().toURL() customClass.addURL(it.toURI().toURL()) } final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo',true, customClass).newInstance( apiSources: [ new ApiSource( springmvc: false, locations: ['com/github/kongchen/swagger/sample/wordnik/resource'], schemes: ['http', 'https'], host: 'petstore.swagger.wordnik.com', basePath: '/api', info: new Info( title: 'Swagger Maven Plugin Sample', version: 'v1', description: 'This is a sample for swagger-maven-plugin', termsOfService: 'http://www.github.com/kongchen/swagger-maven-plugin', contact: new Contact( email: 'kongchen@gmail.com', name: 'Kong Chen', url: 'http://kongch.com' ), license: new License( url: 'http://www.apache.org/licenses/LICENSE-2.0.html', name: 'Apache 2.0' ) ), outputPath: file("${buildDir}/swagger/document.html").path, swaggerDirectory: file("${buildDir}/swagger/swagger-ui").path, templatePath: file("${project(':swagger-maven-example').projectDir}/templates/strapdown.html.hbs") ) ] ) // maven plugin mavenTask.execute() 

Here you can find this example.

+1
source share

All Articles