Friday, May 10, 2019

Swagger Integration In Spring Boot Application

Spring Boot RESTful API Documentation With Swagger 2

 Step -1:  Add maven dependencies into pom.xml

<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.0.0.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
</parent>
.  .  .
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
    <scope>compile</scope>
</dependency>
.  .  .


package javaiq.in.springframework;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 Step -2:  Create Swagger Config file using @Configuration and @EnableSwagger2

  1. @EnableSwagger2 - This is used to enable the swagger configuration during application startup.
  2. Docket -  It is a builder which acts as a primary interface in swagger-springmvc framework. It returns below things.
  3. ApiInfo -  It returns a ApiInfoBuilder which specfies the title,description etc of the Rest API's.
  4. Select() - select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.
  5. Apis -  provides RequestHandlerSelectors which specified basepackage to scan for all the controllers.
  6. Paths() - Provides the mapping endpoints of our API's.
  7. PathSelectors.any() - This is used to add multiple comtroller into swagger-ui. 
 Step -3: add swagger configuration :- SwaggerConfig.java

package javaiq.in.springframework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
 @Bean
 public Docket productApi() {
  return new Docket(DocumentationType.SWAGGER_2).select()
    .apis(RequestHandlerSelectors.basePackage("javaiq.in.springframework.controllers"))
    // .paths(regex("/product.*"))
    // .paths(paths())
    .paths(PathSelectors.any()).build().apiInfo(metaData());
 }

 private ApiInfo metaData() {
  return new ApiInfoBuilder().title("Spring Boot Example With Swagger")
    .description("\"Spring Boot Example With Swagger\"").version("1.0.0")
    .license("Apache License Version 2.0").licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
    .contact(new Contact("Sanjeev Lahariya", "http://javaiq.in", "sanjeevlahariya1812@gmail.com")).build();
 }

 // Describe your apis
 /*
   private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(
   "Hotel Management Rest APIs") .description(
   "This page lists all the rest apis for Hotel Management App.")
   .version("1.0-SNAPSHOT") .build(); }
  */
 // Only select apis that matches the given Predicates.
 private Predicate<String> paths() {
  // Match all paths except /error
  return Predicates.and(PathSelectors.regex("/customer.*"), Predicates.not(PathSelectors.regex("/error.*")));
 }
}


 Step -4:  Add entity class:- Meaasge.java

package javaiq.in.springframework.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Message {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Integer id;
 private String player;
 private String message;

 public Message(String player, String message) {
  this.player = player;
  this.message = message;
 }

 public String getPlayer() {
  return player;
 }

 public void setPlayer(String player) {
  this.player = player;
 }

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }
}

Step -5: Create controller:- MessageController.java

package javaiq.in.springframework.controllers;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javaiq.in.springframework.domain.Message;

@RestController
@RequestMapping("/message")
public class MessageController {

 @RequestMapping(value = "/sendMessage/{messsage}", method = RequestMethod.GET, produces = "application/json")
 public Message message(@PathVariable String messsage) {
  Message msg = new Message(messsage, "Hello admin " + messsage);
  return msg;
 }

}

Test your application with swagger.
http://localhost:8080/swagger-ui.html
http://localhost:8080/v2/api-docs


The above Swagger implementation is without documentation look like this. 


Step -6: Test your application with swagger.
http://localhost:8080/swagger-ui.html

Now let see Spring Boot RESTful API Documentation With Swagger 2.
Note:- Swagger configuration is same as above just need to change in entity/model class & in controller class.
Customer.java

package javaiq.in.springframework.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import io.swagger.annotations.ApiModelProperty;

@Entity
public class Customer {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @ApiModelProperty(notes = "The database generated customer ID", required = true)
 private Integer id;

 @ApiModelProperty(notes = "Name of customer in database")
 private String name;

 @ApiModelProperty(notes = "Address of customer in database")
 private String address;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
}

CustomerController.java

package javaiq.in.springframework.controllers;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javaiq.in.springframework.domain.Customer;
import javaiq.in.springframework.domain.Product;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value = "Customer", description = "Manage Customer Profile", produces = "application/json")
@RequestMapping("/customer")
public class CustomerController {
 
 @ApiOperation(value = "get customer", response = Customer.class)
 @ApiResponses(value = { @ApiResponse(code = 200, message = "Customer Details Retrieved", response = Customer.class),
   @ApiResponse(code = 500, message = "Internal Server Error"),
   @ApiResponse(code = 404, message = "Customer not found") })
 @RequestMapping(value = "/getCustomer", method = RequestMethod.GET, produces = "application/json")
 public ResponseEntity<Customer> getCustomer() {
  Customer cust = new Customer();
  cust.setName("Amit");
  cust.setId(5);
  cust.setAddress("New Delhi");
  return new ResponseEntity<Customer>(cust, HttpStatus.OK);
 }
}


Q- How to change jar/war file name while craete a build in spring application?

<build>
    <finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
</bulid>



No comments:

Post a Comment