Wednesday, December 20, 2023

Building RESTful APIs with Spring Boot and OpenAPI Generator

  • In this Post, we will explore how to create RESTful APIs using Spring Boot and OpenAPI Generator. OpenAPI Generator simplifies the process of building APIs by generating server stubs and client SDKs from OpenAPI Specifications. 
  • We'll go through the steps of setting up a Spring Boot project, integrating OpenAPI Generator, and creating a real-time example API.

What is OpenAPI

  • OpenAPI, formerly known as Swagger, is a set of rules and conventions for building and documenting APIs. It provides a standard way to describe RESTful APIs, making it easier for both humans and computers to understand their capabilities. OpenAPI specifications can be written in YAML or JSON and serve as a contract between API providers and consumers.
Importance of OpenAPI:
  • Documentation:- OpenAPI specifications act as living documentation for your API. They provide a clear and standardized way to understand the API's endpoints, request/response formats, and authentication requirements.
  • Code Generation:- OpenAPI Generator allows for the automatic generation of server stubs and client SDKs in various programming languages. This reduces development time and ensures consistency between the API documentation and its implementation.
  • Interoperability:- By adhering to the OpenAPI standard, APIs become more interoperable. Clients and servers can be developed independently, as long as they follow the agreed-upon OpenAPI specification.

Prerequisites

  • Basic knowledge of Spring Boot
  • Java Development Kit (JDK) installed
  • Your favorite Integrated Development Environment (IDE)

SpringBoot Open API Generator Project 

1. Create OpenAPI spec
  • Begin by architecting the OpenAPI specification for your application, focusing on designing a Customer API. Although real-world APIs are often intricate, let's maintain simplicity for this exercise. 
  • The Swagger Editor provides an effective platform for this task, offering real-time feedback and dynamic Swagger documentation generation. Refer to the official OpenAPI documentation for comprehensive details on the specification.
  • In the header of the OpenAPI specification, include metadata such as the API's title, version, and server information. Employ tags to logically group resources, enhancing overall clarity.
  • The "paths" section delineates specifications for each resource. Initiate with the creation of a Customer using a POST request, encompassing a JSON payload. The "operationId" serves as the method name for code generation. For simplicity, focus on handling successful responses. Schemas, referencing the JSON body, will be explored in-depth later.
  • Next, define a resource enabling the retrieval of a Customer. This resource incorporates a path parameter denoting the customerId for retrieval. In cases where the ID is non-existent, a NOT FOUND response is specified.
  • Conclude the specification with the "components" section, where the utilized schemas are formally defined. The Customer schema and the CustomerFullData schemas share identical properties, excluding the ID. Utilize the "allOf" property for streamlined maintenance.
2. Setting Up the Spring Boot Project:
  • Start by creating a new Spring Boot project using your preferred IDE or Spring Initializr. Include the necessary dependencies, such as Spring Web, in your project.
3. Configure OpenAPI plugin in pom.xml
  • <plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>5.3.0</version> <executions> <execution>
    <goals>
    <goal>generate</goal>
    </goals>
    <configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
    <generatorName>spring</generatorName>
    <packageName>com.springboot.openapi.generator</packageName>
    <apiPackage>com.springboot.openapi.generator.api</apiPackage>
    <modelPackage>com.springboot.openapi.generator.model</modelPackage>
    <!-- Uncomment in order to display the config options -->
    <!-- <configHelp>true</configHelp>-->
    <configOptions>
    <interfaceOnly>true</interfaceOnly>
    </configOptions>
    </configuration>

    </execution>

      </executions>

    </plugin>
4. Generate Code:
  • Run the Maven build to generate code from the OpenAPI Specification.
    • mvn clean install
      Generated Code and Project Structure:
  • OpenAPI Generator will generate code based on your OpenAPI Specification. The generated code typically includes the following components:
  • API Controllers:Spring Boot controllers handling API endpoints.
  • Models:- POJOs representing data structures defined in the OpenAPI Specification.
5. Implementing Controllers:
6. SpringBoot OpenAPI Generator Full Code:
7. Run Your Spring Boot Application:
  • Run command : mvn spring-boot:run
  • Test Add a Customer Foo Bar
  • $ curl -i -X 'POST' \ > 'http://localhost:8080/customer' \ > -H 'accept: application/json' \ > -H 'Content-Type: application/json' \ > -d '{ > "firstName": "Foo", > "lastName": "Bar" > }' Output: HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked
  • Verify whether a Customer can be retrieved by ID:
  • $ curl -i http://localhost:8080/customer/1 Output: HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked {"firstName":"John","lastName":"Doe","customerId":1}
  • Verify whether a NOT FOUND is returned for a non-existing Customer:
  • $ curl -i http://localhost:8080/customer/2 Output: HTTP/1.1 404 Content-Length: 0 Date: Sat, 15 Jan 2022 11:46:18 GMT

Conclusion:

  • You've successfully set up a Spring Boot project with OpenAPI Generator, created an OpenAPI Specification, and implemented controllers. This approach streamlines API development, ensures consistent documentation, and promotes interoperability between API providers and consumers.

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS