spring

Create Models With OpenAPI And Lombok

In the world of no-code development, generating models using OpenAPI with Lombok annotations has become an important task. OpenAPI, a specification for building APIs, seamlessly integrates with Lombok, a Java library, to streamline the model generation process. This approach not only enhances code readability but also significantly reduces boilerplate code. By combining the power of OpenAPI’s API definition capabilities with Lombok’s annotation-based simplifications, developers can efficiently create models that align with API specifications.

1. What is OpenAPI?

OpenAPI, formerly known as Swagger, is a specification for building APIs, providing a standardized way to describe RESTful APIs. It employs a language-agnostic approach, allowing developers to define API functionalities comprehensively.

1.1 Benefits of OpenAPI

  • Interoperability: OpenAPI promotes interoperability by offering a common language for API description, facilitating seamless communication between different systems.
  • Documentation: Automatic generation of comprehensive and human-readable API documentation, enhancing clarity for developers and stakeholders.
  • Code Generation: Enables the generation of client libraries and server stubs in various programming languages, reducing development time and potential errors.
  • Validation: Supports input and output validation, ensuring data consistency and reducing the risk of runtime errors.

1.2 Use Cases of OpenAPI

  • API Development: OpenAPI simplifies the process of designing, documenting, and deploying APIs, fostering collaboration among development teams.
  • Microservices: Ideal for describing microservices interactions, aiding in the understanding and maintenance of complex microservices architectures.
  • Testing: Enables the creation of automated tests based on API specifications, ensuring consistent behavior across different implementations.
  • OpenAPI plays a pivotal role in modern software development, providing a standardized and efficient approach to API design and implementation.

2. What is Lombok?

Lombok is a popular Java library that simplifies the development process by automatically generating boilerplate code (such as getters, setters, constructors, etc.) for Java classes. The name “Lombok” is derived from the Indonesian island of Lombok.

Java developers often find themselves writing a lot of repetitive code for basic class functionality, which can be tedious and error-prone. Lombok helps reduce this boilerplate code by introducing annotations that instruct the compiler to generate the necessary code during compilation.

2.1 Advantages and Disadvantages of Lombok

2.1.1 Advantages

  • Reduces Boilerplate Code: Lombok eliminates the need to write repetitive and mundane code, such as getters, setters, constructors, and equals/hashCode methods. This leads to cleaner and more concise code.
  • Enhances Code Readability: With Lombok annotations, the class code becomes more focused on business logic, making it easier to read and understand.
  • Saves Development Time: Lombok helps developers save time by automating the generation of common code, allowing them to focus on writing more important aspects of the application.
  • Fewer Errors due to Manual Coding: As developers don’t need to manually write repetitive code, the chances of introducing bugs and errors due to manual coding are reduced.
  • Easy to Maintain and Update: Since Lombok-generated code is automatically kept in sync with changes to the class, maintenance, and updates become simpler.

2.1.2 Disadvantages

  • Dependency on External Library: When using Lombok, your project becomes dependent on the Lombok library. This could lead to issues if Lombok’s compatibility with the development environment or future versions becomes a concern.
  • Limited Control over Code Generation: While Lombok simplifies code generation, it might not cater to all custom scenarios. This could limit the developer’s control over how the code is generated.
  • Potential Learning Curve for Beginners: For developers new to Lombok, there might be a learning curve in understanding the various annotations and their usage.
  • IDE Support and Annotation Processors: Some IDEs might not fully support Lombok’s annotations, which could lead to reduced IDE code assistance and error highlighting.
  • Compatibility with Third-Party Tools and Plugins: Lombok-generated code might not always play well with other third-party tools, libraries, or plugins, potentially causing conflicts or unexpected behavior.

3. Generate Models Using OpenAPI With Lombok Annotations

Here’s an example of a Spring Boot application showcasing the utilization of OpenAPI specifications to generate models during compile time. To keep this article straightforward, we’ll omit other aspects and concentrate solely on the generation of models through OpenAPI specifications.

3.1 Create a Spring Boot Project

You can use the Spring Initializr to generate a basic Spring Boot project with the necessary dependencies.

Here’s a list of Maven dependencies you should add to your Spring Boot project (pom.xml) for this tutorial.

  • Spring Boot Starter Web: A starter for building web applications using Spring Boot.
  • Lombok: A library that helps reduce boilerplate code in Java by providing annotations for common tasks.
  • Jackson Databind: Part of the Jackson JSON processing library for handling JSON data.
  • Gson: A library for JSON serialization and deserialization.
  • JavaX Annotation API: An API for adding annotations to Java code.
  • Swagger Annotations: Annotations for use with Swagger, a tool for API documentation.
  • Spring Boot Starter Test: Starter for testing Spring Boot applications.

The project includes Maven build configuration, and specifying plugins for Spring Boot and OpenAPI code generation.

  • Spring Boot Maven Plugin: Configured to use a specific builder for creating a container image and excluding Lombok from the image.
  • OpenAPI Generator Maven Plugin: Generates Java code from an OpenAPI (Swagger) specification, with additional Lombok annotations, and excludes unnecessary files and documentation.

pom.xml

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<optional>true</optional>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
	</dependency>
	<dependency>
		<groupId>com.google.code.gson</groupId>
		<artifactId>gson</artifactId>
		<version>2.8.9</version>
	</dependency>
	<dependency>
		<groupId>javax.annotation</groupId>
		<artifactId>javax.annotation-api</artifactId>
		<version>1.3.2</version>
	</dependency>
	<dependency>
		<groupId>io.swagger</groupId>
		<artifactId>swagger-annotations</artifactId>
		<version>1.6.11</version>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<image>
					<builder>paketobuildpacks/builder-jammy-base:latest</builder>
				</image>
				<excludes>
					<exclude>
						<groupId>org.projectlombok</groupId>
						<artifactId>lombok</artifactId>
					</exclude>
				</excludes>
			</configuration>
		</plugin>

		<plugin>
			<groupId>org.openapitools</groupId>
			<artifactId>openapi-generator-maven-plugin</artifactId>
			<version>4.2.3</version>
			<executions>
				<execution>
					<goals>
						<goal>generate</goal>
					</goals>
					<configuration>
						<inputSpec>${project.basedir}/src/main/resources/petstore.yaml</inputSpec>
						<generatorName>java</generatorName>
						<modelPackage>com.example.demo.model</modelPackage>
						<configOptions>
							<additionalModelTypeAnnotations>
								@lombok.Data
								@lombok.NoArgsConstructor
								@lombok.AllArgsConstructor
							</additionalModelTypeAnnotations>
						</configOptions>
						<generateApis>false</generateApis>
						<generateSupportingFiles>false</generateSupportingFiles>
						<generateApiDocumentation>false</generateApiDocumentation>
					</configuration>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

3.2 Create a Model specification

Generate an API specification using the Pet Store OpenAPI definition, which is required to generate a model during compile time. It’s important to note that, at present, the capability to generate models is limited or nonexistent for other aspects like controllers, services, and helper classes in a Spring Boot application.

src/main/resources/petstore.yaml

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            maximum: 100
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pets"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
components:
  schemas:
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
    Pets:
      type: array
      maxItems: 100
      items:
        $ref: "#/components/schemas/Pet"
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string

4. Generating Model classes

Creating a model from the OpenAPI specification is a straightforward process. Simply go to the project’s root directory and execute the following command:

Command

mvn clean install

The command above will generate Pet.java and Error.java models in the target folder. The generated model classes will include Lombok annotations, effectively functioning as boilerplate code for the rest of the Spring Boot application.

Java OpenAPI Lombok Create Models
Fig. 1: Generated Pet Model class

5. Conclusion

In this tutorial, we explored the process of creating a model enriched with Lombok annotations using the OpenAPI code generator. The inclusion of the additionalModelTypeAnnotations property grants us the flexibility to incorporate the desired Lombok annotations seamlessly.

6. Download the Project

This was a tutorial to generate a model using OpenAPI with Lombok annotations.

Download
You can download the full source code of this example here: Generate Models Using OpenAPI With Lombok Annotations

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button