Code Generation using Swagger Codegen for java spring

Today we will see how to generate code from swagger using swagger codegen. 

Swagger Codegen is an open-source project which allows the generation of API client libraries, server stubs, and documentation automatically from an OpenAPI Specification.

 

We will use the employee management swagger created in the previous blog here.


Swagger codegen Online

In the swagger editor, we have options in the top left to generate code.


swagger codegen client and server code generation online

Swagger codegen support various server and client-side programming language below are supported server language.


swagger codegen server supported code

Supported client-side language


swagger codegen client supported code


Let generate spring code for our swagger. As you see below the generated code contains the src folder which contains java codes and swagger2SpringBoot.java is the main class of spring application which is a starting point of execution.

  • model folder contains all model classes (definition part of swagger)
  • API folder contains all the endpoints defined in our swagger.
  • The configuration folder contains some pre-defined configuration classes that you can delete or use if you want.

swagger codegen spring boot sample example


The src folder looks like below


swagger codegen folder structure

Open any IDE and import the generated code I have imported code in eclipse IDE now we have to implement our business logic in EmployeeApiController class


swagger codegen spring boot project ,maven sample example

The controller class contains the endpoints defined in a swagger.

package io.swagger.api;

@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-07-10T05:10:55.528Z[GMT]")
@RestController
public class EmployeeApiController implements EmployeeApi {

  private static final Logger log = LoggerFactory.getLogger(EmployeeApiController.class);

  private final ObjectMapper objectMapper;

  private final HttpServletRequest request;

  @org.springframework.beans.factory.annotation.Autowired
  public EmployeeApiController(ObjectMapper objectMapper, HttpServletRequest request) {
    this.objectMapper = objectMapper;
    this.request = request;
  }

  public ResponseEntity < Employees > employeeEmployeeidDelete(
    @Parameter( in = ParameterIn.HEADER, description = "used for logging purpose as unqiue idenfier", required = true, schema = @Schema()) @RequestHeader(value = "x-requestid", required = true) String xRequestid,
    @Parameter( in = ParameterIn.PATH, description = "employee id", required = true, schema = @Schema()) @PathVariable("employeeid") String employeeid) {
    // TODO implement business logic
    return new ResponseEntity < Employees > (HttpStatus.NOT_IMPLEMENTED);

  }

  public ResponseEntity < Employees > employeeEmployeeidPut(
    @Parameter( in = ParameterIn.HEADER, description = "used for logging purpose as unqiue idenfier", required = true, schema = @Schema()) @RequestHeader(value = "x-requestid", required = true) String xRequestid,
    @Parameter( in = ParameterIn.PATH, description = "employee id", required = true, schema = @Schema()) @PathVariable("employeeid") String employeeid) {
    // TODO implement business logic
    return new ResponseEntity < Employees > (HttpStatus.NOT_IMPLEMENTED);
  }

  public ResponseEntity < Void > employeePost(
    @Parameter( in = ParameterIn.HEADER, description = "used for logging purpose as unqiue idenfier", required = true, schema = @Schema()) @RequestHeader(value = "x-requestid", required = true) String xRequestid) {
    // TODO implement business logic
    return new ResponseEntity < Void > (HttpStatus.NOT_IMPLEMENTED);
  }
}

Below is generated, model class.


package com.employee.example.model;

/**
 * Employees
 */
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-07-10T12:05:54.514+05:30")


public class Employees extends ArrayList<Employee> implements Serializable {
  private static final long serialVersionUID = 1L;


  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode());
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class Employees {\n");
    sb.append("    ").append(toIndentedString(super.toString())).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}
  

Swagger codegen Cli

We can also do some configurations using swagger codegen CLI to generate code. To do that download the latest swagger-codegen-cli jar file from here. https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.21/

 

Create a file Swagger-codegen-options.json in the root folder and define the following properties check out all available swagger-codegen-options.


{
"basePackage": "com.employee.example",
"modelPackage": "com.employee.example.model",
"apiPackage": "com.employee.example.api",
"invokerPackage": "com.employee.example.gen",
"configPackage": "com.employee.example.config",
"serializableModel": true,
"dateLibrary": "java8-localdatetime",
"java8": true,
"useRuntimeException": false
}

Now open the cmd in the root folder of the project and enter the command

 

To generate spring boot code

 

java -jar swagger-codegen-cli-2.4.21.jar generate -c swagger-codegen-options.json -l spring -i swagger.yaml

 

To get all java related option

 

java -jar swagger-codegen-cli.jar config-help -l java 


swagger codegen spring boot sample example

Post a Comment

Previous Post Next Post

Recent Posts

Facebook