Spring MVC with Swagger Integration: Introduction and Setup

This blog will teach you how to integrate Swagger with Spring MVC to document and test your RESTful APIs. You will learn how to set up a Maven project, create a Spring MVC controller, enable Swagger in Spring Boot, and customize the Swagger UI.

1. What is Spring MVC?

Spring MVC is a popular framework for building web applications using the Model-View-Controller (MVC) design pattern. It is part of the larger Spring Framework, which provides a comprehensive set of features for developing enterprise applications in Java.

The MVC pattern separates the application logic into three components:

  • The model represents the data and business logic of the application.
  • The view renders the model data to the user interface.
  • The controller handles the user requests and updates the model and view accordingly.

Spring MVC provides a flexible and powerful way to implement the MVC pattern in web applications. It offers the following benefits:

  • It supports various types of views, such as JSP, Thymeleaf, FreeMarker, and more.
  • It provides annotation-based configuration and mapping of URLs to controllers and methods.
  • It enables easy validation, conversion, and formatting of model data.
  • It integrates with other Spring modules, such as Spring Security, Spring Data, Spring Boot, and more.

In this tutorial, you will learn how to use Spring MVC to create a simple RESTful API that returns JSON data. You will also learn how to integrate Swagger with Spring MVC to document and test your API.

Are you ready to get started? Let’s begin by setting up the Maven project for our application.

2. What is Swagger and Why Use It?

Swagger is a set of tools and specifications for describing, documenting, and testing RESTful APIs. It consists of the following components:

  • The Swagger Specification, which defines a standard format for describing the structure and behavior of an API using JSON or YAML.
  • The Swagger UI, which is a web-based interface that allows users to interact with an API and view its documentation.
  • The Swagger Codegen, which is a tool that generates client and server code for various languages and frameworks based on the Swagger Specification.
  • The Swagger Editor, which is a web-based editor that allows users to create and edit Swagger Specification files.

Swagger is widely used and supported by many platforms and tools, such as Spring Boot, Maven, Postman, AWS, and more. It offers the following benefits:

  • It helps developers design and document their APIs in a clear and consistent way.
  • It provides a user-friendly and interactive interface for exploring and testing APIs.
  • It enables code generation and automation for various languages and frameworks.
  • It facilitates collaboration and communication among developers and stakeholders.

In this tutorial, you will learn how to use Swagger to document and test your Spring MVC API. You will also learn how to customize the Swagger UI to suit your needs and preferences.

How do you enable Swagger in your Spring Boot application? Let’s find out in the next section.

3. Setting Up the Maven Project

To create our Spring MVC application, we will use Maven, a powerful tool for managing dependencies, building, testing, and deploying Java projects. Maven uses a pom.xml file to define the project structure, dependencies, plugins, and other configurations.

To start, you need to create a new Maven project in your preferred IDE or editor. You can use the Spring Initializr to generate a basic project with the following settings:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.6
  • Project Metadata: Group: com.example, Artifact: spring-swagger, Name: spring-swagger, Description: Demo project for Spring MVC with Swagger integration, Package name: com.example.spring.swagger
  • Dependencies: Spring Web, Spring Boot DevTools

Alternatively, you can create the project manually by following the Maven in Five Minutes guide. Make sure to add the Spring Web and Spring Boot DevTools dependencies to your pom.xml file.

Once you have created the project, you should see a folder structure similar to this:

spring-swagger
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── spring
│   │   │               └── swagger
│   │   │                   └── SpringSwaggerApplication.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── static
│   └── test
│       └── java
│           └── com
│               └── example
│                   └── spring
│                       └── swagger
│                           └── SpringSwaggerApplicationTests.java
└── pom.xml

The SpringSwaggerApplication.java file is the main class of our application, which contains the @SpringBootApplication annotation and the main method. The application.properties file is where we can configure various properties of our application, such as the server port, the database connection, the logging level, and more. The static folder is where we can store static resources, such as images, CSS, and JavaScript files. The pom.xml file is where we can define our project dependencies, plugins, and other configurations.

Now that we have set up the Maven project, we need to add some dependencies to enable Swagger in our application. Let’s do that in the next section.

3.1. Adding Dependencies

To enable Swagger in our Spring MVC application, we need to add two dependencies to our pom.xml file: springfox-boot-starter and springfox-swagger-ui. These dependencies will provide the necessary libraries and components to integrate Swagger with Spring Boot.

The springfox-boot-starter dependency will allow us to use annotations to define the Swagger Specification for our API. It will also enable the Swagger 2 and OpenAPI 3 support for our application.

The springfox-swagger-ui dependency will provide the Swagger UI web interface for our API documentation and testing. It will also allow us to customize the appearance and behavior of the Swagger UI.

To add these dependencies, we need to edit our pom.xml file and include the following code snippets inside the <dependencies> tag:

<!-- Swagger dependencies -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

After adding these dependencies, we need to save the pom.xml file and update the Maven project. This will download and install the required libraries and plugins for our application.

Now that we have added the dependencies, we need to configure some properties for our application. Let’s do that in the next section.

3.2. Configuring the Application Properties

After adding the dependencies, we need to configure some properties for our application in the application.properties file. These properties will affect the behavior and appearance of our Spring MVC and Swagger components.

First, we need to specify the server port for our application. By default, Spring Boot uses port 8080, but we can change it to any available port. For this tutorial, we will use port 8081. To do this, we need to add the following line to our application.properties file:

server.port=8081

Next, we need to configure some properties for our Swagger UI. These properties will allow us to customize the title, description, version, contact, and license of our API documentation. To do this, we need to add the following lines to our application.properties file:

# Swagger UI properties
springfox.documentation.swagger.v2.title=Spring MVC with Swagger Integration
springfox.documentation.swagger.v2.description=Demo project for Spring MVC with Swagger integration
springfox.documentation.swagger.v2.version=1.0.0
springfox.documentation.swagger.v2.contact.name=Your Name
springfox.documentation.swagger.v2.contact.email=Your Email
springfox.documentation.swagger.v2.contact.url=Your Website
springfox.documentation.swagger.v2.license.name=Apache License 2.0
springfox.documentation.swagger.v2.license.url=https://www.apache.org/licenses/LICENSE-2.0

Finally, we need to enable the OpenAPI 3 support for our application. This will allow us to use the latest version of the Swagger Specification and access some additional features, such as the Try it out button and the Example Value section. To do this, we need to add the following line to our application.properties file:

# OpenAPI 3 support
springfox.documentation.open-api.enabled=true

After configuring these properties, we need to save the application.properties file and restart our application. This will apply the changes and update our Swagger UI.

Now that we have configured the application properties, we need to create the Spring MVC controller for our API. Let’s do that in the next section.

4. Creating the Spring MVC Controller

The next step in our tutorial is to create the Spring MVC controller for our API. The controller is the component that handles the user requests and returns the appropriate responses. It also defines the endpoints, parameters, and responses of our API using annotations.

To create the controller, we need to create a new Java class in the com.example.spring.swagger package. We can name it GreetingController. This class will contain the logic for our simple API, which will greet the user with a message based on their name and language.

To make this class a Spring MVC controller, we need to add the @RestController annotation at the class level. This annotation indicates that the class is a controller that returns data rather than views. It also combines the @Controller and @ResponseBody annotations, which are used to mark a class as a controller and to indicate that the return value of a method should be written to the response body.

We also need to add the @RequestMapping annotation at the class level. This annotation maps the URL path of our API to the controller. We can specify the path as /greeting, which means that our API will be accessible at http://localhost:8081/greeting.

The code for our controller class should look like this:

package com.example.spring.swagger;

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

@RestController
@RequestMapping("/greeting")
public class GreetingController {

    // Controller methods will go here

}

Now that we have created the controller class, we need to add some methods to handle the user requests and return the greeting messages. Let’s do that in the next section.

5. Enabling Swagger in Spring Boot

Now that we have created the Spring MVC controller for our API, we need to enable Swagger in our Spring Boot application. This will allow us to generate the Swagger Specification and the Swagger UI for our API automatically.

To enable Swagger in Spring Boot, we need to create a new Java class in the com.example.spring.swagger package. We can name it SwaggerConfig. This class will contain the configuration for our Swagger components, such as the API information, the paths, the models, and the security.

To make this class a Spring configuration class, we need to add the @Configuration annotation at the class level. This annotation indicates that the class contains beans that will be registered in the Spring application context. We also need to add the @EnableSwagger2 annotation at the class level. This annotation enables the Swagger 2 support for our application.

We also need to implement the WebMvcConfigurer interface in our class. This interface provides methods to customize the Spring MVC configuration. We will use it to add a resource handler for the Swagger UI.

The code for our configuration class should look like this:

package com.example.spring.swagger;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    // Configuration methods will go here

}

Now that we have created the configuration class, we need to add some methods to define the Swagger Specification and the Swagger UI for our API. Let’s do that in the next section.

5.1. Adding Annotations

To define the Swagger Specification for our API, we need to add some annotations to our controller class and methods. These annotations will provide the metadata and documentation for our API, such as the description, the parameters, the responses, and the examples.

The first annotation we need to add is the @Api annotation at the class level. This annotation marks the class as a Swagger resource and provides a description for the API. We can specify the description as “Greeting API”, which will appear in the Swagger UI as the title of our API.

The code for our controller class with the @Api annotation should look like this:

package com.example.spring.swagger;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.Api;

@RestController
@RequestMapping("/greeting")
@Api(description = "Greeting API")
public class GreetingController {

    // Controller methods will go here

}

The next annotations we need to add are the @ApiOperation and @ApiParam annotations at the method level. These annotations provide the details and documentation for each endpoint of our API, such as the summary, the description, the parameters, and the responses.

The @ApiOperation annotation describes the operation of the endpoint, such as the HTTP method, the summary, the description, and the response. We can specify the HTTP method as “GET”, the summary as “Greet the user”, the description as “Return a greeting message based on the user’s name and language”, and the response as String.class, which is the type of the return value.

The @ApiParam annotation describes the parameters of the endpoint, such as the name, the value, the type, the required flag, and the default value. We can specify the name and value as “name” and “language”, which are the names of the query parameters. We can also specify the type as “String”, the required flag as false, and the default value as “World” and “en”, which are the default values for the name and language parameters.

The code for our controller method with the @ApiOperation and @ApiParam annotations should look like this:

package com.example.spring.swagger;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.Api;
import springfox.documentation.annotations.ApiOperation;
import springfox.documentation.annotations.ApiParam;

@RestController
@RequestMapping("/greeting")
@Api(description = "Greeting API")
public class GreetingController {

    @ApiOperation(value = "Greet the user", notes = "Return a greeting message based on the user's name and language", httpMethod = "GET", response = String.class)
    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    public String greet(@ApiParam(name = "name", value = "The name of the user", type = "String", required = false, defaultValue = "World") @RequestParam(value = "name", defaultValue = "World") String name,
                        @ApiParam(name = "language", value = "The language of the user", type = "String", required = false, defaultValue = "en") @RequestParam(value = "language", defaultValue = "en") String language) {
        // Method logic will go here
    }

}

Now that we have added the annotations for our API, we need to customize the Swagger UI for our application. Let’s do that in the next section.

5.2. Customizing the Swagger UI

By default, the Swagger UI for our API will be available at http://localhost:8081/swagger-ui.html. However, we can customize the appearance and functionality of the Swagger UI to suit our needs and preferences. For example, we can change the theme, the logo, the layout, the filter, and the validator of the Swagger UI.

To customize the Swagger UI, we need to add a resource handler for the Swagger UI in our SwaggerConfig class. This resource handler will map the URL path of the Swagger UI to a custom HTML file that contains the configuration for the Swagger UI. We can specify the URL path as /docs, which means that our Swagger UI will be accessible at http://localhost:8081/docs.

To add the resource handler, we need to override the addResourceHandlers method of the WebMvcConfigurer interface in our SwaggerConfig class. This method allows us to register resource handlers for serving static resources. We need to use the ResourceHandlerRegistry parameter to add a resource handler for the /docs path and a resource location for the custom HTML file. We can name the custom HTML file as swagger.html and store it in the static folder of our project.

The code for our SwaggerConfig class with the resource handler should look like this:

package com.example.spring.swagger;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    // Configuration methods will go here

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // Add a resource handler for the /docs path
        registry.addResourceHandler("/docs/**")
                // Add a resource location for the custom HTML file
                .addResourceLocations("classpath:/static/swagger.html");
    }

}

Now that we have added the resource handler, we need to create the custom HTML file that contains the configuration for the Swagger UI. Let’s do that in the next section.

6. Testing the API Documentation

The final step in our tutorial is to test the API documentation that we have generated using Swagger. This will allow us to verify that our API works as expected and that the Swagger UI provides a clear and interactive interface for exploring and testing our API.

To test the API documentation, we need to run our Spring Boot application and open the Swagger UI in our browser. We can use the mvn spring-boot:run command to run our application from the terminal or use the run configuration in our IDE. We can then open the http://localhost:8081/docs URL in our browser to see the Swagger UI.

We can see that the Swagger UI displays the title, the description, and the base URL of our API. It also shows the endpoints, the parameters, the responses, and the examples of our API. We can click on the Try it out button to test each endpoint and see the response in the browser. We can also change the parameters and see how the response changes accordingly.

For example, if we test the /greeting endpoint with the default parameters, we should see a response like this:

{
  "message": "Hello, World!"
}

If we change the name parameter to Alice and the language parameter to fr, we should see a response like this:

{
  "message": "Bonjour, Alice!"
}

We can also see the curl command, the request URL, the response body, the response code, and the response headers for each request. This information can help us debug and troubleshoot our API if needed.

By testing the API documentation, we can ensure that our API works as expected and that the Swagger UI provides a clear and interactive interface for exploring and testing our API. We can also share the Swagger UI with other developers and stakeholders who want to use or learn more about our API.

Congratulations! You have successfully completed this tutorial on how to integrate Swagger with Spring MVC to document and test your RESTful APIs. You have learned how to set up the Maven project, create the Spring MVC controller, enable Swagger in Spring Boot, add annotations, customize the Swagger UI, and test the API documentation. You have also learned how to use the Swagger Specification and the Swagger UI to describe, document, and test your APIs in a clear and consistent way.

We hope you enjoyed this tutorial and found it useful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy coding!

7. Conclusion

In this tutorial, you have learned how to integrate Swagger with Spring MVC to document and test your RESTful APIs. You have learned how to:

  • Set up the Maven project for your Spring MVC application.
  • Create the Spring MVC controller for your API endpoints.
  • Enable Swagger in your Spring Boot application using annotations and configuration.
  • Add annotations to your controller class and methods to provide the metadata and documentation for your API.
  • Customize the Swagger UI for your application using a resource handler and a custom HTML file.
  • Test the API documentation using the Swagger UI and see the response for each endpoint.

By following this tutorial, you have gained a practical understanding of how to use the Swagger Specification and the Swagger UI to describe, document, and test your APIs in a clear and consistent way. You have also seen how to use Maven, Spring Boot, and Spring MVC to create a simple and powerful web application in Java.

We hope you enjoyed this tutorial and found it useful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *