Spring Boot Swagger Service
In this tutorial, we will be implementing the service definition of the developed REST APIs using Swagger.
Spring Boot Swagger - Service Definition:
Web applications define many APIs for their normal functionality. As the number of APIs increase, it is essential to provide a common service definition to the client so that the client can understand about the API in detail. It provides the information about the various end-points, parameters, type of request, type of response, etc. Swagger is an open-source software framework by SmartBear software most commonly used for automated documentation, code generation and test-case generation of the RESTful Web Services.
Spring Boot Swagger - Implementation:
We need to add some maven dependency scripts to our pom.xml file to develop the swagger service definition. Add the below maven script to pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
After adding the above script, right click on the project select the option Maven => Update Project. Swagger UI is provided by the script which displays the services available in the web application. We need to add some beans for enabling this. Let us add the below code to our BeansConfiguration.java which we created earlier.
@Configuration
@EnableSwagger2
public class BeansConfiguration {
@Bean
public Docket docket() {
Docket docket = new Docket(DocumentationType.SWAGGER_2);
return docket;
}
}
The above code enables the swagger usage in the project and to view the swagger UI provided by spring boot's swagger dependecy, type the URL http://localhost:8080/swagger-ui.html
as shown in the below figure:
In the above figure notice the two controllers provided, BasicErrorController is provided by spring boot automatically and will be used to display the error messages such as white label error to the client.
The other controller which is the ResourceController was created by us and consists of several GET and POST endpoints that are used for data access. The below figure will be displayed when we click on the above mentioned ResourceController on swagger-ui.html page.
The above figures display the service definition of a GET and POST end points respectively. For post requests, it also provides a way to test the API as shown above. It also provides the input request structure and the possible output response messages that will be displayed.
Conclusion: In this tutorial, we have seen the importance of swagger in understanding the various service definitions of developed REST APIs.