Open In App

How to Generate Spring Boot REST Client with Swagger?

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Boot is a powerful framework for building Java applications, particularly RESTful web services. When developing the REST APIs, it can be crucial to provide documentation that is both user-friendly and interactive. Swagger is an open-source that simplifies this by generating the API documentation automatically. In this article, we will create the Spring Boot REST client that consumes the API documented with Swagger and demonstrate how to configure and use Swagger to document the REST API.

Prerequisites

  • Basic understanding of the Java and Spring Framework.
  • Maven for building dependency management.
  • OpenAPI 3 for API documentation.
  • JDK and IntelliJ Idea installed in your system.

Main Concept: Generate Spring Boot REST Client with Swagger

Swagger allows you to document the API endpoints, request/response formats and available operations in the standardized format. By integrating the Swagger into a Spring Boot application, we can generate the interactive API documentation that enables the developers to explore and test the API directly from the documentation interface.

Generate Spring Boot REST Client with Swagger

Step 1: Create a New Spring Boot Project

Create a new Spring Boot project using IntelliJ IDEA. Choose the following options:

  • Name: spring-swagger-config
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

Project Metadata

Step 2: Add the Dependencies

Add the following Swagger dependencies to your Spring Boot project:

Add the Dependencies

Add Swagger Dependencies

We need to add the Swagger dependencies into the project.

<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui -->
<dependency>
       <groupId>org.springdoc</groupId>
       <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
       <version>2.5.0</version>
</dependency>

Step 3: Project Structure

Once the project is created, the file structure should look like this:

Project Structure

Step 4: Configure the Application Properties

Open the application.properties file and add the following configuration:

spring.application.name=spring-swagger-client
# Swagger related properties
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html

# Path matching strategy
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

Step 5: Configure Swagger

Create a configuration class to set up Swagger. This class will define how Swagger should scan the application and what parts of the API it should document.

Java
package com.gfg.springswaggerclient;

import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // Marks this class as a configuration class
@SecurityScheme(name = "bearerAuth", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer") // Configures security scheme for JWT
public class SwaggerConfig {

    @Bean // Declares this method as a Spring Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components()) // Initializes OpenAPI components
                .info(new Info().title("Sample Swagger API Documentation") // Sets the API title
                        .description("This document provides API details for a sample Spring Boot Project")); // Sets the API description
    }
}

Step 6: Create the Simple Controller Class

Java
package com.gfg.springswaggerclient;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloWorldController {

    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello, World!";
    }
}

Step 7: Main class

No changes are required in the main class.

Java
package com.gfg.springswaggerclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSwaggerClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSwaggerClientApplication.class, args);
    }

}

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-swagger-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-swagger-client</name>
    <description>spring-swagger-client</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui -->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 9: Run the application

Once completed the project, it will start and run at port 8080.

output screenshot

Swagger UI

http://localhost:8080/swagger-ui.html
restswagger output ui

StepUp the Client Application

Step 1: Create a New Spring Boot Project

Create a new Spring Boot project using IntelliJ IDEA. Choose the following options:

  • Name: spring-client
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

Project Metadata

Step 2: Add the Dependencies

Add the following Swagger dependencies to your Spring Boot project:

Add the Dependencies

Step 3: Project Structure

Once the project is created, the file structure should look like this:

Project Structure

Step 4: Configure the Application Properties

Open the application.properties file and add the following configuration:

spring.application.name=spring-client
server.port=8081

Step 5: Define the RestTemplate Bean

We can add the following configuration to the Spring Boot application.

Java
package com.gfg.springclient;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Step 6: Implement the REST Client

We can implement the REST client that consumes the /hello API endpoint documented by the Swagger. We will use the RestTemplate for this purpose.

Java
package com.gfg.springclient;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloWorldClient {

    private final RestTemplate restTemplate;

    public HelloWorldClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getHelloWorld() {
        String url = "http://localhost:8080/api/hello";
        return restTemplate.getForObject(url, String.class);
    }
}

Step 7: Main class

We can add the REST client by calling the getHelloWorld method in the main class.

Java
package com.gfg.springclient;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringClientApplication.class, args);
    }

    @Bean
    CommandLineRunner run(HelloWorldClient helloWorldClient) {
        return args -> {
            String response = helloWorldClient.getHelloWorld();
            System.out.println("Response from API: " + response);
        };
    }

}

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-client</name>
    <description>spring-client</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 8: Run the application

Once run the application. The output should display the message recieved from the API.

Output Screenshot

By following these steps, we have successfully created the Spring Boot REST client that consumes the API documented with Swagger. The Swagger UI can provides and interactive way to explore and test the APIs, while the REST client demonstrates how to consume the API programmatically.

Conclusion

Integrating Swagger with Spring Boot can provides the effortless way to document the REST APIs and make them more accessible to developers. This article demonstrated how to set up the Swagger in a Spring Boot project, create the simple REST API, document it with Swagger and consume it using REST client. With these tools, we can improve the API development workflow and ensure the APIs are well documented and easy to use.


Next Article

Similar Reads