How to Generate Spring Boot REST Client with Swagger?
Last Updated :
22 Aug, 2024
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.
Step 2: Add the Dependencies
Add the following Swagger dependencies to your Spring Boot project:
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:
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.
Swagger UI
http://localhost:8080/swagger-ui.html
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.
Step 2: Add the Dependencies
Add the following Swagger dependencies to your Spring Boot project:
Step 3: Project Structure
Once the project is created, the file structure should look like this:
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.
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.
Similar Reads
Spring Security Integration with Spring Boot
Spring Security is a powerful and customizable authentication and access control framework for Java applications. It provides comprehensive security services for Java EE-based enterprise software applications. This article will integrate Spring Security with a Spring Boot application, covering confi
5 min read
How to Create a Spring Boot Project?
Spring Boot is built on top of the spring and contains all the features of spring. It is one of the most popular frameworks for building Java-based web applications and microservices. It is a favorite among developers due to its rapid, production-ready environment, which allows developers to focus o
6 min read
How to Change the Default Port in Spring Boot?
Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
4 min read
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authenti
2 min read
How to Make REST Calls using FeignClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. FeignClient also known as Spring Cloud OpenFeign is a Decla
12 min read
Spring Boot - Swagger @Parameter vs @Schema
In API development, Swagger is widely used to document the RESTful APIs. Two essential annotations that come into play when defining the API operations and their models are @Parameter and @Schema. Understanding the difference between these annotations is crucial for the developers to accurately desc
5 min read
How to Create a Spring Boot Project with IntelliJ IDEA?
Spring Boot is one of the most popular frameworks for building Java applications, and IntelliJ IDEA is a top-tier IDE for Java development. In this article, we will guide you through the process of creating a Spring Boot project using IntelliJ IDEA. Whether you are a beginner or an experienced devel
3 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTf
7 min read