Generating Java Code from Open API

Introduction:- 

Open API (open application programming interface) Open API Generator can generate code based on an Open API yaml specification. We can generate request models, response models, and controllers of API.

Following are the steps to create java code from Open API:-

Step 1:-Create a yaml file for your API By using this Swagger.io, below is the sample yaml file of create user, you can save this yaml file.

Step 2:- Add this yaml file to your project in the src/main/resources directory.

Step 3:- Define the plugin to the pom.xml file and define the following dependencies to the pom.xml.

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${springfox-version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${springfox-version}</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>org.openapitools</groupId>
        <artifactId>jackson-databind-nullable</artifactId>
        <version>0.1.0</version>
    </dependency>
<!-- Bean Validation API support -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>




<profile>
    <id>create-user</id>
    <build>

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>4.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <skip>false</skip>
                <inputSpec>createUser.yaml</inputSpec>
                <output>${project.basedir}/generated</output>
                <language>spring</language>
                <apiPackage>com.swagger.createUser.api</apiPackage>
                <modelPackage>com.swagger.createUser.models</modelPackage>
            </configuration>
        </execution>
    </executions>
</plugin>

</build>
</profile>


many extra options are available which can be configured in the configOptions section of the configuration section of the OpenAPI plugin.

Step 4:- The last step is to generate code from this yaml file, right click on project -> Run as ->Run configuration

Select your project directory in the Base directory, define your profile name in Profiles: the profile name that you have defined in the pom.xml file, click on Apply and then click on the Run button.

After running this configuration you are able to see a generated folder in your project directory inside that folder you are able to see your request models, response models, and controller of your API.

Leave a Reply