Implement REST API in 5 Easy Steps using OpenAPI Generator & Spring Boot

1. Introduction

OpenAPI Generator allows generation of client libraries, server stubs, and documentation automatically given an specification yaml file. In this blog we will learn & go through the steps required to generate the spring based REST API using OpenAPI Codegen.

1.1 Prerequisites

  • Cloned git repo used to explain the topic.
  • Maven
  • Java
  • IDE of your choice, I have used IntelliJ Community.

2. Specification yaml

Following yaml can be used as a reference point to write specification yaml file for your own project.

openapi: 3.0.0
info:
  title: ContactManager API
  version: 1.0.0
servers:
  - url: http://localhost:8080/
paths:
  /contacts:
    post:
      summary: Create a new contact
      operationId: createContact
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContactDTO'
      responses:
        '201':
          description: Contact created successfully
          content:
            application/json:
              schema:
                type: object
                $ref: '#/components/schemas/ContactDTO'
        '400':
          description: Bad request
    get:
      summary: Search contacts
      operationId: searchContacts
      parameters:
        - name: firstName
          in: query
          description: First name of the contact
          schema:
            type: string
        - name: lastName
          in: query
          description: Last name of the contact
          schema:
            type: string
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/ContactDTO'
        '400':
          description: Bad request
  /contacts/{contactId}:
    put:
      summary: Update contact details
      operationId: updateContact
      parameters:
        - name: contactId
          in: path
          description: ID of the contact to be updated
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContactDTO'
      responses:
        '200':
          description: Contact updated successfully
        '404':
          description: Contact not found
    delete:
      summary: Delete a contact
      operationId: deleteContact
      parameters:
        - name: contactId
          in: path
          description: ID of the contact to be deleted
          required: true
          schema:
            type: string
      responses:
        '204':
          description: Contact deleted successfully
        '404':
          description: Contact not found
components:
  schemas:
    ContactDTO:
      type: object
      properties:
        firstName:
          type: string
        lastName:
          type: string
        email:
          type: string
        phoneNumber:
          type: string
        # Add other contact details as needed

3. Maven Dependencies

Firstly we would require a spring web project, which we can get from spring initializer.

<dependency>
	<groupId>org.openapitools</groupId>
	<artifactId>jackson-databind-nullable</artifactId>
	<version>0.2.6</version>
</dependency>
<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-ui</artifactId>
	<version>1.7.0</version>
</dependency>

After creating & importing the project, we would need to add above jackson-databind-nullable and springdoc dependencies into the pom.xml

4. OpenAPI Generator maven plugin

Add the below plugin into the pom.xml

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>7.1.0</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>
                    ${project.basedir}/src/main/resources/openapi/contactManager.yaml
                </inputSpec>
                <generatorName>spring</generatorName>
                <apiPackage>com.singh.sahil.contactManager.openapi.api</apiPackage>
                <modelPackage>com.singh.sahil.contactManager.openapi.model</modelPackage>
                <supportingFilesToGenerate>
                    ApiUtil.java
                </supportingFilesToGenerate>
                <configOptions>
                    <delegatePattern>true</delegatePattern>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

After adding the above plugin into the pom.xml make a few changes in the above xml code snippet.

  • </inputSpec>: Signifies the path of the specification yaml file.
  • <apiPackage>: Path to the API file generated.
  • <modelPackage>: Path to the models/POJOs generated.

5. Code Generation

To generate the server stub, run the following mvn command.

mvn clean install

After successful run of above command we can find the generated code inside the target/generated-sources folder.

Now as developers we can focus on writing the business logic of the API created.

Spring boot REST API swagger UI, documentation generated by OpenAPI Generator

Conclusion

In this blog post, we’ve showcased how to accelerate development with Spring through the utilization of client- and server-side code generation. By implementing these strategies, developers can significantly expedite their workflow, enabling them to concentrate solely on crafting business logic while delegating tasks such as server-stub and document generation.

You can read more of our blogs here.