Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Java classes for Request and Response objects from Yaml file

We have created a Yaml file using Swagger editor for our APIs specification which includes Base URL, endpoint, Request, Response and Header information etc.. Now I want to implement RESTful web service for these APIs. For that I am thinking of generating my Request and Response Java classes from this Yaml file and was looking for some kind of code generator, preferably a maven plugin/dependency which I could use in my Maven project. I came across this rest client with swagger which talks about using the swagger-codegen Maven plugin, but this is to generate the client which I believe is about generating the client code to consume these RESTful APIs, however my need is to generate classes to be used for service implementation. I will be using Java and Spring framework.

My question is what are the best practices for implementing the RESTful web services in Java when we have Yaml file (API spec created using Swagger editor) and which code generation tools/plugins are available to be used.


EDIT: Just came across this Server stub generator HOWTO, looking further into it.

like image 543
Learner Avatar asked Feb 15 '18 04:02

Learner


People also ask

Can Java read Yaml file?

yaml can be read as an object or map in java. using the jackson-databind module, We can use yamlfactory which parses the physical path of a file and pass it into ObjectMapper, and maps to the same class.

How do you create a class in Java?

To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class. Alternatively, select a Java file or folder in the Project window, or click in a Java file in the Code Editor. Then select File > New > Java Class.

How do I create a Yaml file in Java?

The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream , Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student. yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml. load(inputStream); System.


1 Answers

Swagger-codegen maven plugin is a good option but I suggest you to use jhipster to generate your java project. It generates projects with latest tech stack including spring framework. You can select API-First development in your case. I used it and it was very efficient. You already have Yaml file. Put it in src/main/resources/swagger/api.yml and run

    ./mvnw generate-sources

All java codes will be generated.

like image 88
Mehmet Sunkur Avatar answered Oct 05 '22 00:10

Mehmet Sunkur