Integrating Swagger with Spring Boot helps developers to easily document and interact with RESTful APIs. Swagger offers an easy way to generate API documentation, while Spring Boot simplifies the creation of strong and production-ready applications. This guide will take you through the process of using this set of tools to set up a Spring Boot project, integrating Swagger for REST API documentation, and verifying the setup through testing.
Table of contents
- What is Swagger
- What is Spring Boot
- How to integrate Spring Boot with Swagger
- Benefits of integrating Swagger with Spring Boot
- Conclusion
What is Swagger?
Swagger is an API design and documentation software that helps developers efficiently design, build, document, and test RESTful services. It can automatically generate interactive API documentation, client SDKs, server stub code, and other necessary components. Developers can easily develop, test, and deploy APIs using Swagger, making the process faster and more streamlined. Swagger is also an open-source project.
Swagger is a set of automation tools that accelerates the development and testing of APIs. It reduces errors and simplifies code management, making it an ideal choice for designing and documenting APIs in web applications and cloud services. Swagger provides valuable assistance in designing and documenting APIs, automatically generating code, and testing APIs. More information can be found by reading the official Swagger documentation.
What is Spring Boot?
Spring Boot is an open-source Java framework designed to easily create standalone, production-ready Spring applications. It simplifies the development process by reducing the need for configuration. With Spring Boot, developers can focus more on building features and less on setup. It also includes embedded servers, so you can run applications without needing an external server.
Spring Boot’s powerful Spring framework simplifies the process, making it ideal for building modern Java applications. It provides useful tools like auto-configuration, embedded servers, and production-ready metrics and monitoring, making development faster and easier. Additional information can be found on the official Spring Boot website.
How to integrate Spring Boot with Swagger
Create Spring Boot project
The first thing we’ll do is open Spring Initializr and configure the Project metadata.
Here, we have taken some demo metadata for our sample project:
Project: Maven Project
Language: Java
Spring Boot: Choose the latest stable version
Group: com.example
Artifact: swagger-integration
Name: swagger-integration
Description: Demo project for Swagger integration with Spring Boot
Package name: com.example.swaggerintegration
Packaging: Jar
Java: 21 (or your preferred version)Code language: CSS (css)
Then, add the dependency as Spring Web by clicking the ADD DEPENDENCIES button. The Spring Web dependency is essential because it provides the foundational components required for building web applications, including RESTful APIs, which Swagger will document and visualize.
Click Generate to download the project zip file.
Now that the above steps are done, extract the zip file, place it on your computer to a preferred location, and launch your favorite IDE. In this guide, we’ll be using Eclipse.
Add Swagger dependencies
Once Eclipse opens, click on File > Import.
Select Existing Maven Projects under the Maven category and click Next.
Browse to the location where you extracted the project and select the project folder. Then, click Finish.
In the Project Explorer, find and open the pom.xml file. The pom.xml (Project Object Model) file is important for managing the project’s dependencies, plugins, and other build configurations in a Maven-based project.
Add the following dependencies inside the <dependencies> tag:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>Code language: HTML, XML (xml)
At the time of writing, the Springfox version is 3.0.0. Feel free to check for the latest version when adding this dependency.
Right-click on the project in the Project Explorer. Select Maven > Update Project. Ensure your project is checked and click OK.
Create a configuration class for Swagger
In the src/main/java directory, create a new package.
Create the configuration class by clicking on the newly created package and selecting New > Class.
Open the configuration class file and add the following code snippet:
package com.example.swaggerintegration.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swaggerintegration")) // We have taken sample demo API here; change the base package to add your own API endpoints.
.paths(PathSelectors.any())
.build();
}
}
Code language: Java (java)
In the SwaggerConfig class, we configured Swagger for our Spring Boot application. By annotating the class with @Configuration and @EnableSwagger2, we enabled Swagger support. We defined a Docket bean, which is a primary interface for Swagger’s configuration.
Inside the api method, we specified that Swagger should document all API endpoints found in the com.example.swaggerintegration package using RequestHandlerSelectors.basePackage and include all paths with PathSelectors.any(). This setup ensures that Swagger scans our application for REST endpoints and generates corresponding documentation.
Create a sample REST Controller
Let’s create a simple REST Controller.
In the src/main/java directory, create a new package. Then, right-click on that package and add a new class.
Open that class file and add the following code:
package com.example.swaggerintegration.controller;
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 HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
@GetMapping("/greet")
public String greet() {
return "Integration done by automateNow";
}
}Code language: Java (java)
In the HelloController class, we defined a simple REST controller for our Spring Boot application. By annotating the class with @RestController, we indicated that this class handles HTTP requests and produces responses in JSON format. The @RequestMapping("/api") annotation specifies the base URL for all endpoints in this controller. Inside the class, we created two endpoints: /hello and /greet, both of which respond to HTTP GET requests, defined by the @GetMapping annotation. The /hello endpoint returns “Hello, World!” and the /greet endpoint returns “Integration done by automateNow” when accessed.
Run your Spring Boot application
In Eclipse, find the main application class (SwaggerIntegrationApplication.java) in the src/main/java directory.
Right-click the class and select Run As > Java Application.
The output test result will look like this:
Now, to see this response in Swagger UI, open your browser and enter http://localhost:8080/swagger-ui/. You should see the Swagger UI displaying the endpoints of our rest controller class file. You can interact with them by expanding the endpoints and clicking the Try it out button.
Additional configuration
If your default port (8080) is already in use by another application, then follow these steps:
In your project, navigate to src/main/resources and open the file application.properties.
Add the following line to specify a new port (for example, port 8081):
server.port=8081
After that, run the application again.
Benefits of integrating Swagger with Spring Boot
Swagger automatically creates interactive API docs from your Spring Boot application, making it easier for developers to understand and use the API without manual effort. This lets developers see how the API works and test endpoints directly from the browser.
Integrating Swagger with Spring Boot allows you to document security requirements, such as API keys or OAuth2. This helps users understand how to securely access your API.
Integrating Swagger with Spring Boot simplifies the development process by reducing the need for manual documentation. This means developers can focus more on building features rather than maintaining documentation.
Swagger’s auto-generated documentation saves developers significant time and effort, stopping the need for manual documentation updates and allowing them to focus on more critical tasks.
Final thoughts on Swagger integration with Spring Boot
Integrating Swagger, an open source project, with a Spring Boot application improves the documentation of RESTful web services, making it easier for API developers to understand and interact with them. This step-by-step guide ensures that even beginners can get started with Swagger. Each step is important to ensure successful integration, from creating a Spring Boot project and adding dependencies to configuring Swagger and running the application. Happy testing!
Don’t miss these
Follow our blog
Be the first to know when we publish new content.
How to integrate Swagger to Spring Boot project
- How to find an element in Selenium - October 5, 2024
- Resolved: SessionNotCreatedException - October 2, 2024
- Katalon Recorder Automation Overview - September 12, 2024