Quick Contact



    Spring Boot REST API Documentation with Swagger

    In this tutorial, we will learn how to add step-by-step Swagger to the existing Spring boot application and generate Swagger API documentation.

    In this tutorial, we’ll look at Swagger 2 for a Spring Boot REST web service, using the Springfox implementation of the Swagger 2 specification

    Step 1: Adding the Maven Dependency to Spring Boot Project

    Let’s open pom.xml and below single maven springfox-boot-starter dependency:

    	< dependency>
    	< groupId>io.springfox< /groupId>
    	< artifactId>springfox-boot-starter< /artifactId>
    	< version>3.0.0< /version>
    	< /dependency>

    After adding the springfox-boot-starter dependency, spring boot will auto-configure Swagger in Spring boot so we don’t need to manually add annotations to enable Swagger.

    Access Swagger documentation JSON API

    Here is the URL format:


    Consider we are creating blog app and to verify that Springfox is working, we can visit this URL in our browser:


    Step 2: Integrating Swagger 2 Into the Spring Boot Project

    Let’s create a SwaggerConfig class and annotate with @Configuration annotation. The configuration of Swagger mainly centers around the Docket bean so let’s add the below code to SwaggerConfig class:

    	public class SwaggerConfiguration {
    	privateApiInfoapiInfo() {
    	return new ApiInfo("Blog REST APIs",
    	                "REST APIs for Blog Application",
    	                "Terms of service",
    	new Contact("Ramesh Fadatare", "www.javaguides.net", "ramesh@gmail.com"),
    	                "License of API",
    	                "API license URL",
    	public Docket api() {
    	return new Docket(DocumentationType.SWAGGER_2)

    After defining the Docket bean, it’s select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.

    We can configure predicates for selecting RequestHandlers with the help of RequestHandlerSelectors and PathSelectors. Using any() for both will make documentation for our entire API available through Swagger.

    Step 3: Accessing Swagger UI

    Swagger UI is a built-in solution that makes user interaction with the Swagger-generated API documentation much easier.

    Let’s say we are creating a blog application so in our case, the exact URL will be:


    Customizing Swagger REST Documentation with Annotations

    In order to customize the Swagger documentation, swagger-core offers a set of annotations to declare and manipulate the output.

    You can find more details about swagger annotations on https://github.com/swagger-api/swagger-core/wiki/annotations

    Below code snippet shows how to use @Api and @ApiOperation annotations to provide additional information to REST APIs:

    	@Api(value = "CRUD Rest APIs for Post resources")
    	publicPostController(PostServicepostService) {
    	this.postService = postService;
    	@ApiOperation(value = "Create Post REST API")
    	publicResponseEntity< PostDto>createPost(@Valid@RequestBodyPostDtopostDto){
    	returnnewResponseEntity<>(postService.createPost(postDto), HttpStatus.CREATED);
    	@ApiOperation(value = "Get All Posts REST API")
    	@RequestParam(value = "pageNo", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER, required = false) intpageNo,
    	@RequestParam(value = "pageSize", defaultValue = AppConstants.DEFAULT_PAGE_SIZE, required = false) intpageSize,
    	@RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) StringsortBy,
    	@RequestParam(value = "sortDir", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) StringsortDir
    	returnpostService.getAllPosts(pageNo, pageSize, sortBy, sortDir);
    	@ApiOperation(value = "Get Post By Id REST API")
    	@GetMapping(value = "/api/v1/posts/{id}")
    	publicResponseEntity< PostDto>getPostByIdV1(@PathVariable(name = "id") long id){
    	@ApiOperation(value = "Update Post By Id REST API")
    	publicResponseEntity< PostDto>updatePost(@Valid@RequestBodyPostDtopostDto, @PathVariable(name = "id") long id){
    	PostDtopostResponse = postService.updatePost(postDto, id);
    	returnnewResponseEntity<>(postResponse, HttpStatus.OK);
    	@ApiOperation(value = "Delete Post By Id REST API")
    	publicResponseEntity< String>deletePost(@PathVariable(name = "id") long id){
    	returnnewResponseEntity<>("Post entity deleted successfully.", HttpStatus.OK);
    	Below code snippet shows how to use @ApiModel and @ApiModelProperty annotations to provide additional information about Swagger models:
    	@ApiModel(description = "Post model information")
    	public class PostDto {
    	@ApiModelProperty(value = "Blog post id")
    	private long id;
    	// title should not be null  or empty
    	// title should have at least 2 characters
    	@ApiModelProperty(value = "Blog post title")
    	@Size(min = 2, message = "Post title should have at least 2 characters")
    	private String title;
    	// post description should be not null or empty
    	// post description should have at least 10 characters
    	@ApiModelProperty(value = "Blog post description")
    	@Size(min = 10, message = "Post description should have at least 10 characters")
    	private String description;
    	// post content should not be null or empty
    	@ApiModelProperty(value = "Blog post conent")
    	private String content;
    	@ApiModelProperty(value = "Blog post comments")
    	private Set< CommentDto> comments;


    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.