Spring Boot RESTful API Documentation With Swagger 2
Posted By : Abhishek Saini | 22-Apr-2018
Spring Boot makes it very easy to develop RESTful services. Use Swagger to easily record your RESTful services.
Swagger 2 help for documenting RESTful APIs. Swagger is language independent and can also be extended to new technologies and protocols that go beyond HTTP. The current version defines a set of HTML, JavaScript, and CSS resources to dynamically generate documents with Swagger-compatible APIs. These files are grouped by the Swagger UI project to display the API in the browser. The Swagger user interfaces also help the API developers or consumer to interact with API without implementing implementation logic or any other business logic.
To use this, we need the following dependency declaration in our Maven POM.
io.springfox springfox-swagger2 2.8.0 compile
We also require Swagger UI. To include Swagger UI we need to add
io.springfox springfox-swagger-ui 2.8.0 compile
Now let's suppose ProductController defines the REST API endpoints. The code of ProductController is this.
@RestController
@RequestMapping("/product")
public class ProductController {
private ProductService productService;
@Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}
@RequestMapping(value = "/list", method= RequestMethod.GET)
public Iterable list(Model model){
Iterable productList = productService.listAllProducts();
return productList;
}
}
To Configuring Swagger 2 in the Application, we need
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select() .apis(RequestHandlerSelectors.basePackage("guru.springframework.controllers"))
.paths(regex("/product.*"))
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Hope this help
Thanks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhishek Saini
Abhishek is bright Lead developer with skills in AngularJS and Java. He loves to learn new technologies.