This blog shows how to configure Swagger and add documentation to your Spring MVC RESTful API. It also explains how to use Swagger UI to view and test your API.
1. Introduction
In this tutorial, you will learn how to configure Swagger and add documentation to your Spring MVC RESTful API. You will also learn how to use Swagger UI to view and test your API endpoints.
Swagger is a popular tool for designing, documenting, and testing APIs. It provides a standard way to describe the structure and behavior of your API using a JSON or YAML format. Swagger also generates interactive documentation that allows you to explore and test your API using a web browser.
Spring MVC is a framework for building web applications using the Model-View-Controller pattern. It supports the development of RESTful APIs that can handle various types of requests and responses. Spring MVC also integrates well with Swagger, allowing you to easily document and test your API.
To follow this tutorial, you need to have some basic knowledge of Spring MVC and RESTful APIs. You also need to have a Spring MVC project set up and ready to run. You can use any IDE of your choice, such as Eclipse or IntelliJ IDEA.
By the end of this tutorial, you will be able to:
- Add Swagger dependencies to your Spring MVC project
- Create a Docket bean to configure your API information
- Document your API with Swagger annotations
- Access and use Swagger UI to view and test your API
- Customize Swagger UI to suit your preferences
Are you ready to get started? Let’s begin by learning what Swagger is and why you should use it.
2. What is Swagger and Why Use It?
Swagger is a set of open-source tools that help you design, document, and test your RESTful APIs. It is based on the OpenAPI Specification, which is a standard format for describing the structure and behavior of your API using JSON or YAML.
Swagger consists of three main components:
- Swagger Editor: A web-based editor that lets you write and validate your OpenAPI definition.
- Swagger Codegen: A tool that generates server and client code for your API in various languages and frameworks.
- Swagger UI: A web-based interface that displays your API documentation and allows you to interact with your API endpoints.
Why should you use Swagger for your Spring MVC project? Here are some of the benefits:
- It makes your API more discoverable and understandable for both developers and consumers.
- It simplifies your API development and maintenance by providing a single source of truth for your API specification.
- It enables you to test and debug your API easily and efficiently using Swagger UI.
- It supports code generation and documentation generation for your API in various languages and formats.
- It integrates well with Spring MVC and other Spring Boot features, such as Springfox and Spring Boot Actuator.
How do you use Swagger for your Spring MVC project? In the next section, you will learn how to add Swagger dependencies to your project and create a Docket bean to configure your API information.
2.1. Swagger Features
In this section, you will learn about some of the main features of Swagger that make it a powerful and useful tool for designing, documenting, and testing your APIs. You will also see some examples of how Swagger works in practice.
One of the key features of Swagger is the OpenAPI Specification, which is a standard format for describing the structure and behavior of your API using JSON or YAML. The OpenAPI Specification defines various aspects of your API, such as:
- The paths and operations that your API supports, along with the parameters and responses for each operation.
- The models and schemas that represent the data structures used by your API.
- The security and authentication mechanisms that your API requires or supports.
- The metadata and documentation that provide additional information about your API, such as the title, description, version, license, contact, etc.
Here is an example of a simple OpenAPI Specification for a pet store API:
openapi: 3.0.0 info: title: Pet Store API description: A simple API for managing pets in a pet store. version: 1.0.0 paths: /pets: get: summary: List all pets operationId: listPets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: '200': description: A paged array of pets content: application/json: schema: $ref: '#/components/schemas/Pets' default: description: unexpected error content: application/json: schema: $ref: '#/components/schemas/Error' post: summary: Create a pet operationId: createPets responses: '201': description: Null response default: description: unexpected error content: application/json: schema: $ref: '#/components/schemas/Error' /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: '#/components/schemas/Pet' default: description: unexpected error content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: Pet: type: object required: - id - name properties: id: type: integer format: int64 name: type: string tag: type: string Pets: type: array items: $ref: '#/components/schemas/Pet' Error: type: object required: - code - message properties: code: type: integer format: int32 message: type: string
Another feature of Swagger is the Swagger Editor, which is a web-based editor that lets you write and validate your OpenAPI Specification. You can use the Swagger Editor to create and edit your API definition, as well as to preview and test your API using the Swagger UI.
You can access the Swagger Editor online at https://editor.swagger.io/, or you can download and run it locally. You can also import and export your API definition from and to various formats, such as JSON, YAML, or URL.
A third feature of Swagger is the Swagger Codegen, which is a tool that generates server and client code for your API in various languages and frameworks. You can use the Swagger Codegen to generate code that implements your API specification, as well as to generate documentation and test cases for your API.
You can access the Swagger Codegen online at https://generator.swagger.io/, or you can download and run it locally. You can also customize and extend the code generation process using templates and plugins.
A fourth feature of Swagger is the Swagger UI, which is a web-based interface that displays your API documentation and allows you to interact with your API endpoints. You can use the Swagger UI to explore and test your API using a web browser, as well as to share and collaborate on your API with others.
You can access the Swagger UI online at https://petstore.swagger.io/, or you can download and run it locally. You can also customize and style the Swagger UI using themes and options.
As you will see, Swagger offers many features that make it a powerful and useful tool for designing, documenting, and testing your APIs. In the next section, you will learn about some of the benefits of using Swagger for your Spring MVC project.
2.2. Swagger Benefits
In the previous section, you learned about some of the main features of Swagger that make it a powerful and useful tool for designing, documenting, and testing your APIs. In this section, you will learn about some of the benefits of using Swagger for your Spring MVC project.
One of the benefits of using Swagger for your Spring MVC project is that it makes your API more discoverable and understandable for both developers and consumers. By using the OpenAPI Specification, you can provide a clear and consistent description of your API, which can help you communicate and collaborate with other developers who work on or use your API. By using the Swagger UI, you can provide an interactive and user-friendly documentation of your API, which can help you attract and retain consumers who want to explore and test your API.
Another benefit of using Swagger for your Spring MVC project is that it simplifies your API development and maintenance by providing a single source of truth for your API specification. By using the Swagger Editor, you can create and edit your API definition in a fast and easy way, without having to write or update multiple files or documents. By using the Swagger Codegen, you can generate code that implements your API specification, without having to write or update code manually. By using the Swagger UI, you can test and debug your API easily and efficiently, without having to use external tools or applications.
A third benefit of using Swagger for your Spring MVC project is that it enables you to test and debug your API easily and efficiently using the Swagger UI. The Swagger UI allows you to view and interact with your API endpoints using a web browser, without having to install or configure any software or hardware. You can see the request and response details, such as the URL, method, headers, body, status, and time. You can also modify the request parameters and body, and see the changes in the response. You can also see the validation errors and warnings, if any, and fix them accordingly.
A fourth benefit of using Swagger for your Spring MVC project is that it supports code generation and documentation generation for your API in various languages and formats. By using the Swagger Codegen, you can generate server and client code for your API in different languages and frameworks, such as Java, Python, Ruby, C#, etc. You can also generate documentation and test cases for your API in different formats, such as HTML, PDF, Markdown, etc. You can also customize and extend the code generation process using templates and plugins.
A fifth benefit of using Swagger for your Spring MVC project is that it integrates well with Spring MVC and other Spring Boot features, such as Springfox and Spring Boot Actuator. Springfox is a library that automatically generates the OpenAPI Specification and the Swagger UI for your Spring MVC project, based on your annotations and configurations. Spring Boot Actuator is a feature that provides various endpoints for monitoring and managing your Spring Boot application, such as health, metrics, info, etc. You can use Swagger to document and test these endpoints, as well as to customize their appearance and behavior.
As you can see, Swagger offers many benefits that make it a valuable and convenient tool for your Spring MVC project. In the next section, you will learn how to add Swagger dependencies to your project and create a Docket bean to configure your API information.
3. How to Add Swagger to Spring MVC Project
In this section, you will learn how to add Swagger dependencies to your Spring MVC project and create a Docket bean to configure your API information. You will also learn how to use Springfox, a library that integrates Swagger with Spring MVC and Spring Boot.
The first step is to add the Swagger dependencies to your project. You can use Maven or Gradle to manage your dependencies. You need to add two dependencies: springfox-swagger2 and springfox-swagger-ui. The former provides the core functionality of Swagger, such as generating the OpenAPI Specification and the Swagger UI. The latter provides the web interface for viewing and testing your API documentation.
If you are using Maven, you can add the following dependencies to your pom.xml file:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency>
If you are using Gradle, you can add the following dependencies to your build.gradle file:
dependencies { implementation 'io.springfox:springfox-swagger2:3.0.0' implementation 'io.springfox:springfox-swagger-ui:3.0.0' }
The second step is to create a Docket bean to configure your API information. A Docket is a builder that allows you to define various properties of your API, such as the title, description, version, contact, license, etc. You can also specify the packages or classes that contain your API controllers and methods, as well as the paths and operations that you want to include or exclude from your documentation.
You can create a Docket bean in a configuration class that is annotated with @EnableSwagger2. This annotation enables the Swagger support for your project. You can also use the @Configuration and @ComponentScan annotations to mark the class as a configuration component and to scan the packages for your API controllers.
Here is an example of a configuration class that creates a Docket bean for the pet store API:
@Configuration @EnableSwagger2 @ComponentScan(basePackages = "com.example.petstore.controller") public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfo( "Pet Store API", "A simple API for managing pets in a pet store.", "1.0.0", "Terms of service", new Contact("John Doe", "www.example.com", "john@example.com"), "License of API", "API license URL", Collections.emptyList()); } }
The third step is to use Springfox, a library that integrates Swagger with Spring MVC and Spring Boot. Springfox automatically generates the OpenAPI Specification and the Swagger UI for your project, based on your annotations and configurations. You can use the standard Spring MVC annotations, such as @RestController, @RequestMapping, @GetMapping, @PostMapping, etc., to define your API controllers and methods. You can also use the Swagger-specific annotations, such as @ApiOperation, @ApiParam, @ApiResponse, etc., to provide additional information and documentation for your API.
Here is an example of a controller class that uses Spring MVC and Swagger annotations for the pet store API:
@RestController @RequestMapping("/pets") @Api(tags = "Pets") public class PetController { @GetMapping @ApiOperation(value = "List all pets", notes = "Returns a paged array of pets") public ResponseEntity<List<Pet>> listPets(@ApiParam(value = "How many items to return at one time (max 100)", example = "10") @RequestParam(value = "limit", required = false) Integer limit) { // ... } @PostMapping @ApiOperation(value = "Create a pet", notes = "Creates a new pet in the store") public ResponseEntity<Void> createPet(@ApiParam(value = "Pet object that needs to be added to the store", required = true) @RequestBody Pet pet) { // ... } @GetMapping("/{petId}") @ApiOperation(value = "Info for a specific pet", notes = "Returns a single pet") public ResponseEntity<Pet> showPetById(@ApiParam(value = "The id of the pet to retrieve", required = true) @PathVariable("petId") String petId) { // ... } }
By following these three steps, you have successfully added Swagger to your Spring MVC project. You can now access the Swagger UI at http://localhost:8080/swagger-ui/ and view and test your API documentation.
3.1. Adding Dependencies
In this section, you will learn how to add the Swagger dependencies to your Spring MVC project using Maven or Gradle. You will need to add two dependencies: springfox-swagger2 and springfox-swagger-ui. These dependencies provide the core functionality of Swagger, such as generating the OpenAPI Specification and the Swagger UI for your project.
If you are using Maven, you can add the following dependencies to your pom.xml file:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency>
If you are using Gradle, you can add the following dependencies to your build.gradle file:
dependencies { implementation 'io.springfox:springfox-swagger2:3.0.0' implementation 'io.springfox:springfox-swagger-ui:3.0.0' }
After adding the dependencies, you need to refresh your project and make sure that the dependencies are resolved correctly. You can use the mvn clean install or gradle clean build commands to do that.
By adding the Swagger dependencies, you have enabled the Swagger support for your project. In the next section, you will learn how to create a Docket bean to configure your API information.
3.2. Creating Docket Bean
In this section, you will learn how to create a Docket bean to configure your API information. A Docket is a builder that allows you to define various properties of your API, such as the title, description, version, contact, license, etc. You can also specify the packages or classes that contain your API controllers and methods, as well as the paths and operations that you want to include or exclude from your documentation.
To create a Docket bean, you need to create a configuration class that is annotated with @EnableSwagger2. This annotation enables the Swagger support for your project. You can also use the @Configuration and @ComponentScan annotations to mark the class as a configuration component and to scan the packages for your API controllers.
In the configuration class, you need to create a bean method that returns a Docket object. You can use the @Bean annotation to mark the method as a bean provider. You can also use the Docket constructor to specify the documentation type as DocumentationType.SWAGGER_2.
Then, you can use the select() method to create an ApiSelectorBuilder object, which allows you to select the APIs that you want to document. You can use the apis() and paths() methods to filter the APIs by request handlers and path patterns. You can use the RequestHandlerSelectors and PathSelectors classes to provide various criteria for filtering, such as any, none, base package, class annotation, method annotation, regex, etc.
Finally, you can use the build() method to build the Docket object. You can also use the apiInfo() method to provide an ApiInfo object, which contains the metadata and documentation for your API. You can use the ApiInfo constructor to specify the title, description, version, terms of service, contact, license, etc. of your API.
Here is an example of a configuration class that creates a Docket bean for the pet store API:
@Configuration @EnableSwagger2 @ComponentScan(basePackages = "com.example.petstore.controller") public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfo( "Pet Store API", "A simple API for managing pets in a pet store.", "1.0.0", "Terms of service", new Contact("John Doe", "www.example.com", "john@example.com"), "License of API", "API license URL", Collections.emptyList()); } }
By creating a Docket bean, you have configured your API information for Swagger. In the next section, you will learn how to document your API with Swagger annotations.
3.3. Configuring API Information
In this section, you will learn how to configure your API information using the Docket bean. The Docket bean is a Swagger configuration class that allows you to specify various properties of your API, such as the title, description, version, contact, license, and so on. You can also define the scope and visibility of your API documentation using the Docket bean.
To create a Docket bean, you need to add the @EnableSwagger2
annotation to your main application class. This annotation enables the Swagger support for your Spring MVC project. Then, you need to create a @Bean
method that returns a Docket object. You can use the Docket
constructor to specify the type of your API, such as DocumentationType.SWAGGER_2
. You can also use the select()
method to create an ApiSelectorBuilder
object, which allows you to filter the API endpoints that you want to document. For example, you can use the apis()
and paths()
methods to select the controllers and methods that match certain criteria, such as annotations or regex patterns.
Here is an example of how to create a Docket bean for your Spring MVC project:
@EnableSwagger2 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfo( "Spring MVC with Swagger Integration", "This is a sample API for demonstrating how to configure Swagger and add documentation to your Spring MVC RESTful API.", "1.0", "Terms of service", new Contact("John Doe", "www.example.com", "john@example.com"), "License of API", "API license URL", Collections.emptyList()); } }
In this example, the Docket bean selects all the controllers that have the @RestController
annotation and all the paths that match any pattern. It also defines the API information using the apiInfo()
method, which returns an ApiInfo
object with the specified parameters. You can customize these parameters according to your needs.
Once you have created the Docket bean, you can run your Spring MVC project and access the Swagger UI at http://localhost:8080/swagger-ui.html
.
As you will see, the Swagger UI displays the API information that you have configured using the Docket bean. You can also expand the controllers and methods to see the details of each endpoint, such as the HTTP method, parameters, responses, and so on.
In the next section, you will learn how to document your API with Swagger annotations, which allow you to add more information and descriptions to your controllers and methods.
4. How to Document API with Swagger Annotations
In this section, you will learn how to document your API with Swagger annotations, which allow you to add more information and descriptions to your controllers and methods. Swagger annotations are Java annotations that you can use to annotate your Spring MVC classes and methods. They provide metadata about your API, such as the operation name, summary, description, parameters, responses, tags, and so on. You can also use Swagger annotations to customize the behavior and appearance of your API documentation and Swagger UI.
To use Swagger annotations, you need to add the io.swagger.annotations
package to your project dependencies. You can do this by adding the following dependency to your pom.xml
file:
io.springfox springfox-swagger2 2.9.2
There are many Swagger annotations that you can use to document your API, but here are some of the most common ones:
@ApiOperation
: This annotation is used to describe a single API operation. You can use it to specify the operation name, summary, description, tags, response type, and so on. You can also use it to hide or show the operation in the Swagger UI.@ApiParam
: This annotation is used to describe a single parameter of an API operation. You can use it to specify the parameter name, description, type, format, default value, required status, and so on. You can also use it to hide or show the parameter in the Swagger UI.@ApiResponse
: This annotation is used to describe a single response of an API operation. You can use it to specify the response code, message, type, and so on. You can also use it to provide examples of the response body.@ApiModel
: This annotation is used to describe a model class that represents a request or response body. You can use it to specify the model name, description, and so on. You can also use it to reference other models or properties.@ApiModelProperty
: This annotation is used to describe a property of a model class. You can use it to specify the property name, description, type, format, required status, and so on. You can also use it to hide or show the property in the Swagger UI.
Here is an example of how to use Swagger annotations to document a controller class and its methods:
@RestController @RequestMapping("/api/users") @Api(tags = "User Management") public class UserController { @Autowired private UserService userService; @GetMapping @ApiOperation(value = "Get All Users", response = User[].class) public List getAllUsers() { return userService.getAllUsers(); } @GetMapping("/{id}") @ApiOperation(value = "Get User By ID", response = User.class) public User getUserById(@PathVariable @ApiParam(value = "User ID", required = true) Long id) { return userService.getUserById(id); } @PostMapping @ApiOperation(value = "Create User", response = User.class) public User createUser(@RequestBody @ApiParam(value = "User Data", required = true) User user) { return userService.createUser(user); } @PutMapping("/{id}") @ApiOperation(value = "Update User", response = User.class) public User updateUser(@PathVariable @ApiParam(value = "User ID", required = true) Long id, @RequestBody @ApiParam(value = "User Data", required = true) User user) { return userService.updateUser(id, user); } @DeleteMapping("/{id}") @ApiOperation(value = "Delete User") @ApiResponses(value = { @ApiResponse(code = 200, message = "User deleted successfully"), @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathVariable @ApiParam(value = "User ID", required = true) Long id) { userService.deleteUser(id); } }
In this example, the controller class has the @Api
annotation to specify the tag name for the API group. Each method has the @ApiOperation
annotation to specify the operation name, response type, and so on. The parameters and request bodies have the @ApiParam
annotation to specify the parameter name, description, required status, and so on. The delete method has the @ApiResponses
annotation to specify the possible responses and their messages.
Once you have added the Swagger annotations to your controller class and methods, you can run your Spring MVC project and access the Swagger UI at http://localhost:8080/swagger-ui.html
.
As you will see, the Swagger UI displays the API annotations that you have added to your controller class and methods. You can also expand the operations and parameters to see the details and descriptions that you have provided. You can also use the Try it out button to test your API endpoints and see the responses.
In the next section, you will learn how to access and use Swagger UI to view and test your API documentation.
4.1. Documenting Controllers and Methods
In this section, you will learn how to document your controllers and methods using the @ApiOperation
and @ApiParam
annotations. These annotations allow you to provide more information and descriptions about your API operations and parameters, such as the name, summary, response type, required status, and so on. You can also use these annotations to customize the visibility and behavior of your API documentation and Swagger UI.
The @ApiOperation
annotation is used to describe a single API operation. You can use it to annotate your controller methods that handle the requests and responses for your API endpoints. The @ApiOperation
annotation has several attributes that you can use to specify the properties of your operation, such as:
value
: The name of the operation.notes
: The summary or description of the operation.response
: The class that represents the response body of the operation.tags
: The tags that group the operations by categories.hidden
: A boolean value that indicates whether the operation should be hidden or shown in the Swagger UI.
Here is an example of how to use the @ApiOperation
annotation to document a controller method that handles a GET request to get a user by ID:
@GetMapping("/{id}") @ApiOperation(value = "Get User By ID", notes = "This operation returns a user by their ID.", response = User.class, tags = "User Management") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); }
The @ApiParam
annotation is used to describe a single parameter of an API operation. You can use it to annotate your controller method parameters that represent the request parameters or body of your API endpoints. The @ApiParam
annotation has several attributes that you can use to specify the properties of your parameter, such as:
name
: The name of the parameter.value
: The description of the parameter.required
: A boolean value that indicates whether the parameter is mandatory or optional.defaultValue
: The default value of the parameter.hidden
: A boolean value that indicates whether the parameter should be hidden or shown in the Swagger UI.
Here is an example of how to use the @ApiParam
annotation to document a controller method parameter that represents the user ID:
@GetMapping("/{id}") @ApiOperation(value = "Get User By ID", notes = "This operation returns a user by their ID.", response = User.class, tags = "User Management") public User getUserById(@PathVariable @ApiParam(value = "User ID", required = true) Long id) { return userService.getUserById(id); }
By using the @ApiOperation
and @ApiParam
annotations, you can provide more information and descriptions about your API operations and parameters, which will make your API documentation more clear and understandable. You can also use these annotations to control the visibility and behavior of your API documentation and Swagger UI, which will make your API more user-friendly and interactive.
In the next section, you will learn how to document your API responses using the @ApiResponse
annotation, which allows you to specify the possible responses and their messages for your API operations.
4.2. Documenting Parameters and Responses
In this section, you will learn how to document your parameters and responses using the @ApiParam
and @ApiResponse
annotations. These annotations allow you to provide more information and descriptions about your API parameters and responses, such as the name, type, format, required status, default value, and so on. You can also use these annotations to customize the visibility and behavior of your API documentation and Swagger UI.
The @ApiParam
annotation is used to describe a single parameter of an API operation. You can use it to annotate your controller method parameters that represent the request parameters or body of your API endpoints. The @ApiParam
annotation has several attributes that you can use to specify the properties of your parameter, such as:
name
: The name of the parameter.value
: The description of the parameter.required
: A boolean value that indicates whether the parameter is mandatory or optional.defaultValue
: The default value of the parameter.hidden
: A boolean value that indicates whether the parameter should be hidden or shown in the Swagger UI.
Here is an example of how to use the @ApiParam
annotation to document a controller method parameter that represents the user ID:
@GetMapping("/{id}") @ApiOperation(value = "Get User By ID", notes = "This operation returns a user by their ID.", response = User.class, tags = "User Management") public User getUserById(@PathVariable @ApiParam(value = "User ID", required = true) Long id) { return userService.getUserById(id); }
The @ApiResponse
annotation is used to describe a single response of an API operation. You can use it to annotate your controller method or class to specify the possible responses and their messages for your API endpoints. The @ApiResponse
annotation has several attributes that you can use to specify the properties of your response, such as:
code
: The HTTP status code of the response.message
: The message or description of the response.response
: The class that represents the response body of the response.examples
: The examples of the response body in different formats.
Here is an example of how to use the @ApiResponse
annotation to document a controller method that handles a DELETE request to delete a user by ID:
@DeleteMapping("/{id}") @ApiOperation(value = "Delete User") @ApiResponses(value = { @ApiResponse(code = 200, message = "User deleted successfully"), @ApiResponse(code = 404, message = "User not found") }) public void deleteUser(@PathVariable @ApiParam(value = "User ID", required = true) Long id) { userService.deleteUser(id); }
By using the @ApiParam
and @ApiResponse
annotations, you can provide more information and descriptions about your API parameters and responses, which will make your API documentation more clear and understandable. You can also use these annotations to control the visibility and behavior of your API documentation and Swagger UI, which will make your API more user-friendly and interactive.
In the next section, you will learn how to document your models and fields using the @ApiModel
and @ApiModelProperty
annotations, which allow you to specify the properties and descriptions of your request and response body classes.
4.3. Documenting Models and Fields
In this section, you will learn how to document your models and fields using the @ApiModel
and @ApiModelProperty
annotations. These annotations allow you to specify the properties and descriptions of your request and response body classes, such as the name, type, format, required status, and so on. You can also use these annotations to customize the visibility and behavior of your API documentation and Swagger UI.
The @ApiModel
annotation is used to describe a model class that represents a request or response body. You can use it to annotate your model classes that are used as the input or output of your API operations. The @ApiModel
annotation has several attributes that you can use to specify the properties of your model, such as:
value
: The name of the model.description
: The description of the model.reference
: The reference to another model or property.subTypes
: The subtypes of the model.
Here is an example of how to use the @ApiModel
annotation to document a model class that represents a user:
@ApiModel(value = "User", description = "A user entity") public class User { private Long id; private String name; private String email; private String role; // getters and setters }
The @ApiModelProperty
annotation is used to describe a property of a model class. You can use it to annotate your model class fields that represent the attributes of your request or response body. The @ApiModelProperty
annotation has several attributes that you can use to specify the properties of your property, such as:
name
: The name of the property.value
: The description of the property.required
: A boolean value that indicates whether the property is mandatory or optional.example
: An example value of the property.hidden
: A boolean value that indicates whether the property should be hidden or shown in the Swagger UI.
Here is an example of how to use the @ApiModelProperty
annotation to document a property of a model class that represents the user ID:
@ApiModel(value = "User", description = "A user entity") public class User { @ApiModelProperty(name = "id", value = "The user ID", required = true, example = "1") private Long id; private String name; private String email; private String role; // getters and setters }
By using the @ApiModel
and @ApiModelProperty
annotations, you can provide more information and descriptions about your models and fields, which will make your API documentation more clear and understandable. You can also use these annotations to control the visibility and behavior of your API documentation and Swagger UI, which will make your API more user-friendly and interactive.
In the next section, you will learn how to access and use Swagger UI to view and test your API documentation.
5. How to Access and Use Swagger UI
In this section, you will learn how to access and use Swagger UI to view and test your API documentation. Swagger UI is a web-based interface that displays your API documentation and allows you to interact with your API endpoints. You can use Swagger UI to explore the features and functionalities of your API, as well as to test and debug your API easily and efficiently.
To access Swagger UI, you need to run your Spring MVC project and open the following URL in your browser: http://localhost:8080/swagger-ui.html
.
As you will see, Swagger UI displays the API information that you have configured using the Docket bean and the Swagger annotations. You can also see the list of controllers and methods that represent your API endpoints, grouped by tags. You can expand each controller and method to see the details and descriptions of each operation, such as the HTTP method, parameters, responses, and so on.
To use Swagger UI, you can follow these steps:
- Select the controller and method that you want to test from the list.
- Click on the Try it out button to enable the testing mode.
- Enter the values for the parameters that you want to send with the request. You can also use the default values or examples provided by the Swagger annotations.
- Click on the Execute button to send the request to your API endpoint.
- View the response that your API returns, including the status code, headers, and body. You can also see the curl command and the request URL that Swagger UI generates for your request.
Swagger UI sends the request with the parameter value of 1 and receives the response with the status code of 200 and the user data in the body. You can also see the curl command and the request URL that Swagger UI generates for your request.
By using Swagger UI, you can view and test your API documentation in a convenient and interactive way. You can also use Swagger UI to discover and learn more about the features and functionalities of your API, as well as to test and debug your API easily and efficiently.
In the next section, you will learn how to customize Swagger UI to suit your preferences, such as changing the theme, layout, and logo of your API documentation.
5.1. Viewing API Documentation
In this section, you will learn how to view your API documentation using Swagger UI. Swagger UI is a web-based interface that displays your API documentation and allows you to interact with your API endpoints. You can use Swagger UI to explore the features and functionalities of your API, as well as to test and debug your API easily and efficiently.
To view your API documentation, you need to run your Spring MVC project and open the following URL in your browser: http://localhost:8080/swagger-ui.html
.
As you will see, Swagger UI displays the API information that you have configured using the Docket bean and the Swagger annotations. You can also see the list of controllers and methods that represent your API endpoints, grouped by tags. You can expand each controller and method to see the details and descriptions of each operation, such as the HTTP method, parameters, responses, and so on.
By viewing your API documentation, you can get a clear and comprehensive overview of your API, as well as learn more about the features and functionalities of your API. You can also use Swagger UI to test and debug your API, which will be covered in the next section.
5.2. Testing API Endpoints
In this section, you will learn how to test your API endpoints using Swagger UI. Swagger UI is a web-based interface that displays your API documentation and allows you to interact with your API endpoints. You can use Swagger UI to explore the features and functionalities of your API, as well as to test and debug your API easily and efficiently.
To test your API endpoints, you need to run your Spring MVC project and open the following URL in your browser: http://localhost:8080/swagger-ui.html
.
As you will see, Swagger UI displays the API information that you have configured using the Docket bean and the Swagger annotations. You can also see the list of controllers and methods that represent your API endpoints, grouped by tags. You can expand each controller and method to see the details and descriptions of each operation, such as the HTTP method, parameters, responses, and so on.
To test your API endpoints, you can follow these steps:
- Select the controller and method that you want to test from the list.
- Click on the Try it out button to enable the testing mode.
- Enter the values for the parameters that you want to send with the request. You can also use the default values or examples provided by the Swagger annotations.
- Click on the Execute button to send the request to your API endpoint.
- View the response that your API returns, including the status code, headers, and body. You can also see the curl command and the request URL that Swagger UI generates for your request.
Swagger UI sends the request with the parameter value of 1 and receives the response with the status code of 200 and the user data in the body. You can also see the curl command and the request URL that Swagger UI generates for your request.
By testing your API endpoints, you can verify the functionality and performance of your API, as well as identify and fix any errors or bugs that may occur. You can also use Swagger UI to learn more about the features and functionalities of your API, which will be covered in the next section.
5.3. Customizing Swagger UI
In this section, you will learn how to customize Swagger UI to suit your preferences, such as changing the theme, layout, and logo of your API documentation. Swagger UI is a web-based interface that displays your API documentation and allows you to interact with your API endpoints. You can use Swagger UI to explore the features and functionalities of your API, as well as to test and debug your API easily and efficiently.
To customize Swagger UI, you need to add some configuration properties to your application.properties file. These properties allow you to modify the appearance and behavior of your Swagger UI, such as the color scheme, the default expansion mode, the display options, and so on. You can find the full list of configuration properties and their descriptions in the Springfox documentation.
Here are some examples of how to customize Swagger UI using the configuration properties:
- To change the theme of your Swagger UI, you can use the
springfox.documentation.swagger-ui.theme
property. You can choose from three themes:DEFAULT
,FLATTOP
, andMUTED
. For example, to use the muted theme, you can add the following property to your application.properties file:
- To change the theme of your Swagger UI, you can use the
springfox.documentation.swagger-ui.theme=MUTED
- To change the layout of your Swagger UI, you can use the
springfox.documentation.swagger-ui.doc-expansion
property. You can choose from four layouts:NONE
,LIST
,FULL
, andOPERATION
. For example, to use the operation layout, which expands only the operations and not the tags, you can add the following property to your application.properties file:
- To change the layout of your Swagger UI, you can use the
springfox.documentation.swagger-ui.doc-expansion=OPERATION
- To change the logo of your Swagger UI, you can use the
springfox.documentation.swagger-ui.logo
property. You can specify the URL of the image that you want to use as the logo, as well as the link that the logo should redirect to. For example, to use the Spring Boot logo and link it to the Spring Boot website, you can add the following property to your application.properties file:
- To change the logo of your Swagger UI, you can use the
springfox.documentation.swagger-ui.logo=https://spring.io/images/projects/spring-boot-7f2e24fb962501672cc91ccd285ed2ba.svg springfox.documentation.swagger-ui.logo-url=https://spring.io/projects/spring-boot
By customizing Swagger UI, you can make your API documentation more appealing and user-friendly, as well as reflect your personal or professional style. You can also use Swagger UI to view and test your API documentation, which will be covered in the previous sections.
In the next and final section, you will learn how to conclude your tutorial and provide some additional resources for further learning.
6. Conclusion
In this tutorial, you have learned how to configure Swagger and add documentation to your Spring MVC RESTful API. You have also learned how to use Swagger UI to view and test your API endpoints, as well as to customize Swagger UI to suit your preferences.
By using Swagger, you can make your API more discoverable and understandable for both developers and consumers. You can also simplify your API development and maintenance by providing a single source of truth for your API specification. Moreover, you can enable your API testing and debugging using Swagger UI, which allows you to interact with your API endpoints in a convenient and interactive way.
Some of the key points that you have learned in this tutorial are:
- Swagger is a set of open-source tools that help you design, document, and test your RESTful APIs.
- Swagger is based on the OpenAPI Specification, which is a standard format for describing the structure and behavior of your API using JSON or YAML.
- Swagger consists of three main components: Swagger Editor, Swagger Codegen, and Swagger UI.
- Swagger integrates well with Spring MVC and other Spring Boot features, such as Springfox and Spring Boot Actuator.
- To add Swagger to your Spring MVC project, you need to add the Swagger dependencies and create a Docket bean to configure your API information.
- To document your API with Swagger annotations, you need to add the Swagger annotations to your controllers and methods, such as @Api, @ApiOperation, @ApiParam, @ApiResponse, and so on.
- To access and use Swagger UI, you need to run your Spring MVC project and open the Swagger UI URL in your browser.
- To customize Swagger UI, you need to add some configuration properties to your application.properties file, such as springfox.documentation.swagger-ui.theme, springfox.documentation.swagger-ui.doc-expansion, and springfox.documentation.swagger-ui.logo.
We hope that you have enjoyed this tutorial and found it useful for your Spring MVC projects. If you want to learn more about Swagger and Spring MVC, you can check out the following resources:
- Swagger official website
- Spring MVC official website
- Springfox official website
- Swagger 2 Documentation for Spring REST API
- Spring MVC Tutorial
Thank you for reading this tutorial and happy coding!