如何使用多个Yaml文件生成openAPI代码

时间:2019-09-26 14:06:00

标签: java gradle openapi swagger-codegen openapi-generator

我有两个Yaml文件,customer.yaml和employee.yaml。如何在单个项目中从这两个Yaml文件生成Java代码。我正在使用gradle,我知道单个yaml的任务规范,但是如何指定多个yaml。我应该在单个openApiGenerator下指定多个inputSpec吗?如果是,那么确切的语法是什么。下面是build.gradle文件中的openApiGenerator任务。

``
openApiGenerate {
    generatorName = "spring"
    apiPackage = "com.xxx.generated.controller"
    modelPackage = "com.xxx.generated.model"
    inputSpec = "$rootDir//schema/employee.yaml".toString()
    outputDir = "$rootDir/generated".toString()
    configOptions = [
        dateLibrary: "java8"
    ]
    systemProperties = [
        invoker : "false", 
        generateSupportingFiles: "true"
    ]
    additionalProperties = [
        interfaceOnly : "true",
    ]
}
 ``

我听说过openApiGenerators任务,该任务列出了通过Open API Generators可用的生成器,但是找不到使用它的方法。

4 个答案:

答案 0 :(得分:1)

我成功地为项目中的每个yaml文件动态创建了任务。我正在使用gradle 4.8.1,但我认为这也适用于下一版本。

import groovy.io.FileType
import org.openapitools.generator.gradle.plugin.tasks.GenerateTask

plugins {
    id "org.openapi.generator" version "4.1.3"
}

//here we are going to store swagger files
def swaggerList = []

//iteration by swagger file root folder and save into swaggerList variable
def dir = new File("$rootDir/src/main/resources/api/".toString())
dir.eachFileRecurse(FileType.FILES) { file ->
    if (file.getName().endsWith(".yaml"))
        swaggerList << file
}

// Iterate on all swagger files and generate a task for each one with the nomenclature openApiGenerate + swagger name
swaggerList.each {
    println it.path
    def apiName = it.getName().replace(".yaml", "");

    tasks.create("openApiGenerate" + apiName.capitalize(), GenerateTask.class, {
        generatorName = "jaxrs-spec"
        inputSpec = "$rootDir/src/main/resources/api/".toString() + "${apiName}.yaml"
        outputDir = "$buildDir/generated/openapi".toString()
        apiPackage = "my.package.rest.api.definition.".toString() + "${apiName}"
        modelPackage = "my.package.rest.api.model.".toString() + "${apiName}"
        templateDir = "$rootDir/src/main/resources/api/templates".toString()
        //    https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/jaxrs-spec.md
        configOptions = [
                dateLibrary: "java8",
                java8: true,
                useBeanValidation: true,
                interfaceOnly: true,
                useOptional: true,
                useLombok: true
        ]
    })
}

sourceSets {
    main {
        java {
            srcDir("$buildDir/generated/openapi/src/gen/java")
            srcDir("$buildDir/generated/openapi/src/main/java")
        }
    }
}

在此之后,如果我有一个名为login.yaml的文件,以及另一个名为user.yaml user.yaml的文件,我将调用下一个gradle任务:

gradle openApiGenerateLogin

gradle openApiGenerateUser

答案 1 :(得分:1)

同样的问题,不同的解决方案。我真的很喜欢在单独的文件中工作的想法,但是,当在开发团队内共享规范或将其导入 postman、insomnia 或某些 API 网关等工具时,单个文件确实更准确和简单。

因此,我建议在此任务中使用 openapi-merger-plugin。它就像一个魅力。

这是我解决这个问题的方法:

// Merging all OpenAPI Files
openApiMerger {
    inputDirectory.set(file("${rootDir}/src/main/resources/api/".toString()))
    output {
        directory.set(file("${buildDir}/generated/openapi/".toString()))
        fileName.set("openapi")
        fileExtension.set("yaml")
    }
    openApi {
        openApiVersion.set("3.0.1")
        info {
            title.set("Open API Merger")
            description.set("All files merged by open api merger")
            version.set("${project.version}".toString())
            termsOfService.set("http://openapimerger.com/terms-of-service")
            contact {
                name.set("OpenApiMerger Team")
                email.set("openapi@sample.com")
                url.set("http://openapimerger.com")
            }
            license {
                name.set("Apache License v2.0")
                url.set("http://apache.org/v2")
            }
        }
        externalDocs {
            description.set("External docs description")
            url.set("http://external-docs.com/uri")
        }
    }
}

// Generating code only once
openApiGenerate {
    generatorName   = "spring"
    inputSpec       = "${buildDir}/generated/openapi/openapi.yaml"
    outputDir       = "${buildDir}/generated/openapi"
    packageName     = "com.xxx.generated"
    apiPackage      = "com.xxx.generated.controller"
    modelPackage    = "com.xxx.generated.model"
    modelNameSuffix = ""
    validateSpec    = true
    configOptions   = [
        dateLibrary         : "java8",
        interfaceOnly       : "true",
        swaggerDocketConfig : "false"
    ]
}

// Making generated source visible (classpath)
sourceSets {
    main {
        java {
            srcDir "${buildDir}/generated/openapi/src/main/java"
        }
    }
}

// Integrating plugin tasks with compiling
tasks.openApiGenerate {
    dependsOn  tasks.mergeOpenApiFiles
}
compileJava {
    dependsOn  tasks.openApiGenerate
    source "${buildDir}/generated/openapi/src/main/java"
}

答案 2 :(得分:0)

在build.gradle中添加了以下代码,因此我能够生成Java代码。将spec1和spec2 yaml文件复制到架构文件夹下。此外,您需要在build.gradle中配置openApi插件和依赖项。

task buildPaymentClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){
generatorName = "spring"
inputSpec = "$rootDir//schema/spec1.yaml".toString()
outputDir = "$rootDir/generated".toString()
apiPackage = "com.abc.code.generated.controller"
modelPackage = "com.abc.code.generated.model"
configOptions = [
        dateLibrary: "java8"
]
systemProperties = [
    invoker : "false", 
    generateSupportingFiles: "true"
]
additionalProperties = [
    interfaceOnly : "true",
]

}

openApiGenerate {
    generatorName = "spring"
    apiPackage = "com.abc.code.generated.controller"
    modelPackage = "com.abc.code.generated.model"
    inputSpec = "$rootDir//schema/spec2.yaml".toString()
    outputDir = "$rootDir/generated".toString()
    configOptions = [
        dateLibrary: "java8"
    ]
    systemProperties = [
        invoker : "false", 
        generateSupportingFiles: "true"
    ]
    additionalProperties = [
        interfaceOnly : "true",
    ]
}

compileJava.dependsOn buildPaymentClient, tasks.openApiGenerate 

答案 3 :(得分:0)

在我的情况下,我使用相同的任务选项,并且只使用不同规范的 yml 文件名,所以这是我的解决方案:

假设您有 2 个 swagger yml 文件:

  • src/main/resources/swagger/api1.yml
  • src/main/resources/swagger/api2.yml

那么:

swagger.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.openapitools:openapi-generator-gradle-plugin:${openapiPluginDependencyVersion}"
    }
}
apply plugin: "org.openapi.generator"

void createOpenApiGenerateTask(String ymlName) {
    String taskName = "openApiGenerate_" + ymlName;
    task(taskName, type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
        inputSpec = "$rootDir/src/main/resources/swagger/${ymlName}.yml".toString()
        // other common task options goes here...
        // e.g.
        // outputDir = "$buildDir/openapi".toString()
        // apiPackage = "com.example.api"
        // ...
    }
    compileJava.dependsOn(taskName)

}

String[] ymlNames = [
        "api1",
        "api2"
]
for (String ymlName : ymlNames) {
    createOpenApiGenerateTask(ymlName);
}

sourceSets {
    main {
        java {
            srcDir file("${project.buildDir.path}/openapi/src/main/java")
        }
    }
}

gradle.properties

openapiPluginDependencyVersion=4.3.0

build.gradle

apply from: "gradle/swagger.gradle"