Opposite of: Generate Spring MVC controller from Swagger/OpenAPI
I need to integrate my Spring Boot project with a remote server exposing Swagger OpenApis. I can successfully download the swagger.json
descriptor from the service, but I would like some automated help in generating REST stubs for a number of Java methods. I am using Gradle. I prefer to commit the swagger.json
into my project to both be able to build offline (the remote services aren't exposed) and leverage Gradle's input caching.
So far I could leverage Swagger generator for Gradle to do the biggest part of work.
I could try
apply plugin: 'org.hidetake.swagger.generator'
dependencies {
swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.5' // or Swagger Codegen V3
swaggerCodegen 'org.openapitools:openapi-generator-cli:3.3.4' // or OpenAPI Generator
}
swaggerSources {
remoteservice{
inputFile = file("${project.rootDir}/gradle/swagger-remoteservice.json")
code {
language = 'spring'
}
}
}
The output was a fully fledged Gradle Spring Boot project in build/swagger-code-remoteservice
also containing a Spring Boot executable.
I had to copy the parts I was interested to:
*Api
interfaceThen I had to implement a Spring service leveraging RestTemplate to perform the Swagger operations. Since there are a number of operations to perform, it will take time.
Additional code I had to write
public class ApiRestImpl implements Api, InitializingBean {
private RestOperations restTemplate;
@Override
public void afterPropertiesSet() throws Exception {
restTemplate = new RestTemplateBuilder()
... //authorization
.build();
}
@Override
public ResponseEntity<Item> getById(Integer id, Boolean bool) {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(properties.getUrl() + "/api/v1/Items/{id}")
.queryParam("bool", bool
return restTemplate.getForEntity(
uriBuilder.toUriString(),
Item.class,
id
);
}
}
I would like to be generated a fully (or almost fully) working client, possibly based on RestTemplate
. Something I can integrate in my own calling code to perform the REST operation.
I could see that Spring Boot projects use a build/generated
directory that gets included into the classpath
In this case, I don't like controllers to be generated and eventually scanned at runtime, so I had to copy the output to the source directory.
You could try to use the OpenAPI gradle plugin. The java
client generator has a library option "resttemplate
".