Participated in the Java community event "JJUG CCC 2019 Fall". The story of creating a super-simple OpenAPI inspired by the content of the "API server development using OpenAPI Specification 3.0 that is not Swagger" that I heard there. (Shallow)
Write OpenAPI using Spring Boot
Rule: ** Generation gap pattern ** → Do not edit the automatically generated class file.
Use the sample in OAS (OpenAPI Specification)
https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v3.0/petstore.yaml
Use Gradle plugin [openapi-generator-gradle-plugin]. Gradle plugin that automatically generates code from API definition file.
build.gradle
plugins {
id "org.openapi.generator" version "4.2.1"
}
Set to include automatically generated class files at compile time
build.gradle
compileJava.dependsOn tasks.openApiGenerate
sourceSets.main.java.srcDir "${openApiGenerate.outputDir.get()}/src/main/java"
sourceSets.main.resources.srcDir
The execution example of openapi-generator-gradle-plugin can be almost copied. Just manipulate the config file to create an interface.
build.gradle
//https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-gradle-plugin
openApiGenerate {
generatorName = "spring"
//Config settings
configFile = "$rootDir/specs/config.json".toString()
//Sample API specification
inputSpec = "$rootDir/specs/petstore-v3.0.yaml".toString()
outputDir = "$buildDir/generated".toString()
apiPackage = "org.openapi.example.api"
invokerPackage = "org.openapi.example.invoker"
modelPackage = "org.openapi.example.model"
configOptions = [
dateLibrary: "java8"
]
systemProperties = [
modelDocs: 'false'
]
}
config.json
{
"interfaceOnly": true
}
Automatic class generation is OK with Gradle task [openApiGenerate].
When the task is executed, the following Java files are automatically generated
Generate a controller by implementing from the automatically generated interface
PetsApiController.java
@RestController
public class PetsApiController implements PetsApi{
@Override
public ResponseEntity<List<Pet>> listPets(@Valid Integer limit) {
System.out.println("Here list pet");
return new ResponseEntity<>(HttpStatus.OK);
}
}
Complete! !!
https://github.com/harutotanabe09/SpringBootOpenAPIBegin
Documents are automatically generated using the OpenAPI Document Tool (redoc).
docker run -it --rm -p 80:80 \
-v $(pwd)/specs/petstore-v3.0.yaml:/usr/share/nginx/html/swagger.yaml \
redocly/redoc
http://localhost/
Output image: Output API parameters and return values on an easy-to-read screen based on the definition file
API server development with OpenAPI Specification 3.0, not Swagger https://www.slideshare.net/techblogyahoo/swagger-openapi-specification-30-api
Recommended Posts