2016-09-21 137 views
8

我想使用swagger-codegen來生成REST客戶端和可能的靜態HTML文檔。如何使用gradle生成swagger.json?

但是,swagger-codegen需要swagger.json來輸入。

我知道,我可以從配備Swagger的正在運行的REST服務器獲取此信息。

但是有沒有辦法從我的Java代碼直接獲取swagger.json - 即使用源代碼中的gradle生成swagger.json - 而不需要在Web容器中運行應用程序,並指定curl或瀏覽器它?

+0

我仍在研究它。 – tbsalling

+0

https://github.com/gigaSproule/swagger-gradle-plugin 你試過這個插件嗎?它聲稱完全按照你的要求做。 –

+0

在使用swagger-gradle-plugin時,我遇到以下錯誤:com.fasterxml.jackson.databind.JsonMappingException:由於輸入結束 at [Source:UNKNOWN;行:1,列:0] – lex

回答

1

的主要思想是招搖,Maven的插件和Java類添加到類路徑buildScript能夠在gradle這個使用它們,像這樣:

buildscript { 
    repositories { 
     mavenCentral() 
    } 

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

,其中在第一線依賴關係從子項目獲取swagger庫,第二行獲取應包含swagger註釋的類。

在這之後,你可以在調用的gradle Maven插件作爲一個簡單的Java類:

// 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: '[email protected]', 
             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你可以找到這個例子。

2

這是一個有點老,但我想知道一模一樣......總之我已經開始與研究:

  • 樣本春天啓動的應用程序暴露簡約的REST API;
  • API方法的Swagger註釋;
  • Springfox;
  • Gradle作爲構建工具;

我設法生成JSON規範與使用兩種不同的方法構建神器:

  1. 通過使用swagger-maven-plugin of kongchengradle port
  2. (不知道這是否值得,因爲它反正啓動服務器)通過執行生成規範的集成測試(Spring的模擬MVC)。我借用here的想法。

我總結了我的研究在一個簡單的項目位於here。請參閱Automation部分。包括代碼和示例。

相關問題