Generate a Feign Client API from the Contract
-
Import
GenerateTask
(start ofbuild.gradle
)build.gradleimport org.openapitools.generator.gradle.plugin.tasks.GenerateTask
-
We need Spring Cloud Starter OpenFeign, Feign OkHttp, Feign Jackson, and Feign Gson dependencies. Add them in the
build.gradle
dependencies section:build.gradleimplementation 'org.springframework.cloud:spring-cloud-starter-openfeign:4.2.1'
implementation 'io.github.openfeign:feign-okhttp:13.5'
implementation 'io.github.openfeign:feign-jackson:13.5'
implementation 'io.github.openfeign:feign-gson:13.5' -
Configure a new openapi-generator task (bottom of
build.gradle
):build.gradletasks.register("openApiGenerate_feign_jsonplaceholder", GenerateTask) {
apiPackage = "com.typicode.jsonplaceholder.api".toString()
configOptions = [
"feignClient": "true",
"interfaceOnly": "true",
"useEnumCaseInsensitive": "true",
"useJakartaEe": "true"
]
generateApiTests = false
generateApiDocumentation = false
generateModelTests = false
generateModelDocumentation = false
generatorName = "java"
inputSpec = "$rootDir/src/main/resources/openapi/jsonplaceholder.yaml".toString()
library = "feign"
modelPackage = "com.typicode.jsonplaceholder.model".toString()
outputDir = layout.buildDirectory.dir("generated/sources/openapi").get().asFile.toString()
}- You can find more information about the different possible configurations in the OpenAPI Generator Gradle Plugin GitHub page.
- Personal recommendations:
- In
apiPackage
use the url we are going to integrate in java-style, and end in.api
(jsonplaceholder.typicode.com
->com.typicode.jsonplaceholder.api
) - Same idea for
modelPackage
(jsonplaceholder.typicode.com
->com.typicode.jsonplaceholder.model
)
- In
- It is important to make sure that
inputspec
is pointing to the desired OpenAPI Specification YAML file.
-
Ensure
compileJava
now depends on both OpenAPI generation tasks:build.gradletasks.named('compileJava') {
dependsOn 'openApiGenerate', 'openApiGenerate_feign_jsonplaceholder'
} -
Now that everything is set up, run the Build Task. When the task finishes, If you check the
build\generated\sources\openapi
folder, you’ll find a newjsonplaceholder.typicode.com
folder with the representation of the OpenAPI Specification in Java code, ready to be used.
Commit the progress so far.
git add .
git commit -m "generated secondary adapter external api code from an openapi specification"