Swagger And Spring Boot (Rest Documentation)

Please Learning Swagger documentation for rest.

To Add Swagger to your application

add the depedencies :

      <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>

And then create create swagger class configuration, example : SwaggerConfiguration class

@Configuration
public class SwaggerConfig {
 
    @Bean
    public Docket productAPI(){
       return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.diarycoding"))
                .paths(PathSelectors.regex("/api.*"))
                .build()
                .apiInfo(metaInfo());
    }
    private ApiInfo metaInfo(){
        return new ApiInfo(
                "Spring boot Swagger",
                "Learning Swagger",
                "1.0",
                "Tearm Of Service",
                new Contact("diarycoding",
                        "www.diarycoding.com",
                        "kreasikudeveloper@gmail.com"),
                "Apache License Version 2.0",
                "https://www.apache.org/license.html",
                new ArrayList<>()
        );
    }
 
}

Add annotation on @ApiOperation

@ApiOperation(value = "Get All Data",
        responseContainer = "List",
        produces = "application/json",
        response = Product.class)
@GetMapping("/")
public Iterable<Product> getProduct(){
    return products;
}

@ApiModel and @ApiModelProperty
this is used for tell consumer application
about information the property (response/ request)
example :

@Data
@AllArgsConstructor
@ApiModel(value = "Product Model For display and Saving Data")
public class Product {
    private String id;
    @ApiModelProperty(notes = "Code Product",
            required = true,
            allowEmptyValue = false,
            dataType = "String"
            )
    private String code;
    private String name;
    private Long stock;
 
}

How to Run Application :

In Server :

mvn spring-boot:run

Open in Browser :

http:localhost:8080/swagger-ui.html

www.diarycoding.com

Leave a Comment.