IT|軟體|測試|Swagger RESTful API 調適工具

使用 Swagger 建立 PDF 文件



Swagger 是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件 Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。

[Spring Boot 集成 Swagger]

[POM]

pom.xml
<!-- swagger2 集成 -->
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
    </dependency>

    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
    </dependency>

Spring boot 版本
---------------
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.7.RELEASE</version>
        <relativePath/>
</parent>

Spring cloud 版本
---------------
<dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-parent</artifactId>
         <version>Camden.RELEASE</version> <!-- 需搭配 1.4.7 -->
         <type>pom</type>
         <scope>import</scope>
</dependency>

[Cofig]

Swagger2Config.java 內容
@Configuration
@EnableSwagger2
public class Swagger2Config {

      @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .produces(Sets.newHashSet("application/json"))
                    .consumes(Sets.newHashSet("application/json"))
                    .protocols(Sets.newHashSet("http", "https"))
                    .apiInfo(apiInfo())
                    .forCodeGeneration(true)
                    .useDefaultResponseMessages(false)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.wistron.api.controller.swagger")) // 指定 controller 存放的目陸路徑
                    .paths(PathSelectors.any())
                    .build();
        }

        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("[FLO-EXPO] RES API Services") // 標題
                    .description("自駕車行車資訊服務接口") // 描述
                    .version("v1")
                    .license("")
                    .licenseUrl("")
                    .build();
        }

}

[bean]

Params.java
@Data
public class Params{
    
    @ApiModelProperty(value = "開始時間(ex.2018-12-21T00:00:00)",required=true)
    private String sdate;
    @ApiModelProperty(value = "結束時間(ex.2018-12-21T23:59:59)",required=true)
    private String edate;   
    
    public Params() {}
    
}

CarGPS.java
@Component
@Data
@ApiModel(description = "自駕車行車資訊")
@Document(collection = "CarGPS")
@CompoundIndexes({@CompoundIndex(name ="carDriverID_timeStamp_idx",def="{'carDriverID_timeStamp_idx': 1, 'carDriverID_timeStamp_idx': 1}")})
public class CarGPS implements Serializable{
    
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "車輛編號")
    @Field("carDriverID")
    @Indexed(unique = false)
    private int carDriverID;

    @ApiModelProperty(value = "經度")
    @Field("carLat")
    private double carLat;
    

    @ApiModelProperty(value = "緯度")
    @Field("carLot")
    private double carLon;
    
    
    @ApiModelProperty(value = "秒速")
    @Field("carSpeed")
    private double carSpeed;
    
    
    @ApiModelProperty(value = "行車方位")
    @Field("heading")
    private float heading;
    
    
    @ApiModelProperty(value = "時間戳記")
    @Field("timeStamp")
    private long timeStamp;
    
    
    public CarGPS(int carDriverID) {
        this.carDriverID = carDriverID;
    }
    
    public CarGPS carGPSFactory(String str) {
        CarGPS carGPS = new CarGPS();
        // 開始的時間戳 (2015-01-01)
        long TWEPOCH = 1540000000000L;
        
        carGPS.setCarDriverID(Integer.parseInt(JsonUtil.parserJsonToString(str, "driver_id")));    
        carGPS.setCarLat(Double.parseDouble(JsonUtil.parserJsonToString(str, "latitude")));
        carGPS.setCarLon(Double.parseDouble(JsonUtil.parserJsonToString(str, "longitude")));
        carGPS.setCarSpeed(Double.parseDouble(JsonUtil.parserJsonToString(str, "speed")));
        carGPS.setHeading(Float.parseFloat(JsonUtil.parserJsonToString(str, "heading")));
        carGPS.setTimeStamp(Long.parseLong(JsonUtil.parserJsonToString(str, "timestamp")) + TWEPOCH);
    
        return carGPS;
     }


[repository]
public interface CarGPSRepository extends CrudRepository<CarGPS, Integer> {
    CarGPS findTopByCarDriverIDOrderByTimeStampDesc(int carDriverID); // 根據 {車輛編號} 取得最近一筆資料
    CarGPS findTop100ByCarDriverIDOrderByTimeStampDesc(int carDriverID); // 根據 {車輛編號} 取得最近一筆資料
    List<CarGPS> findByCarDriverIDAndTimeStampBetween(int carDriverID,long sDate,long eDate); // 根據 {車輛編號}、{日期區間} 查詢行車資料
}



[service]

ICarGPSService.java
public interface ICarGPSService {
    
        public void saveCarGPS(CarGPS carGPS);
        public CarGPS listLastByCarDriverIDCarGPS(int carDriverID);
        public List<CarGPS> listLast100ByCarDriverIDCarGPS(int carDriverID);
        public List<CarGPS> listCarGPS(int carDriverID,long sDate,long eDate);
    
}


[Controller]

CarGPS.java
@Api(value = "API 服務")
@RestController
@RequestMapping("/api/v1/device")
@Slf4j
public class CarGPSCtl {
    
    @Autowired ICarGPSService iCarGPSService;    
    
    @RequestMapping(value = "/cargps/{driver_id}/rawdata", method = {RequestMethod.GET}, produces={"application/json;charset=UTF-8","application/json;charset=UTF-8"})
    @ApiOperation(value = "根據 {車輛編號} 查詢最近 1 筆行車資料", response = CarGPS.class)
    // 定義返回值意義
    @ApiResponses({
         @ApiResponse(code = 400, message = "服務器內部異常"),
         @ApiResponse(code = 401, message = "Unauthorized"),
         @ApiResponse(code = 402, message = "Forbidden"),
         @ApiResponse(code = 404, message = "Not Found"),
         @ApiResponse(code = 500, message = "權限不足")})
    @ApiImplicitParams({
        @ApiImplicitParam(name ="driver_id",value = "車輛編號",dataType = "int",paramType = "path",required = true)
        })
    @ResponseBody
    public CarGPS queryLastByDriverID(@PathVariable("driver_id") int carDriverID){
       log.info(LogUtil.concat("API","queryLastByDriverID"));
       CarGPS carGPS =  iCarGPSService.listLastByCarDriverIDCarGPS(carDriverID);
       if(carGPS != null) {
           return carGPS;
       }else {
           return new CarGPS(carDriverID);
       }
    }
    
    @RequestMapping(value = "/cargps/{driver_id}/100/rawdata", method = {RequestMethod.GET}, produces={"application/json;charset=UTF-8","application/json;charset=UTF-8"})
    @ApiOperation(value = "根據 {車輛編號} 查詢最近 100 筆行車資料", response = CarGPS.class)
    // 定義返回值意義
    @ApiResponses({
         @ApiResponse(code = 400, message = "服務器內部異常"),
         @ApiResponse(code = 401, message = "Unauthorized"),
         @ApiResponse(code = 402, message = "Forbidden"),
         @ApiResponse(code = 404, message = "Not Found"),
         @ApiResponse(code = 500, message = "權限不足")})
    @ApiImplicitParams({
        @ApiImplicitParam(name ="driver_id",value = "車輛編號",dataType = "int",paramType = "path",required = true)
        })
    @ResponseBody
    public List<CarGPS> queryLast100ByDriverID(@PathVariable("driver_id") int carDriverID){
       log.info(LogUtil.concat("API","queryLastByDriverID"));
       List<CarGPS> listCarGPS =  iCarGPSService.listLast100ByCarDriverIDCarGPS(carDriverID);
       if(listCarGPS != null) {
           return listCarGPS;
       }else {
           return new ArrayList<CarGPS>();
       }
    }

    @RequestMapping(value = "/cargps/{driver_id}/rawdata", method = {RequestMethod.POST}, produces={"application/json;charset=UTF-8","application/json;charset=UTF-8"})
    @ApiOperation(value = "根據 {車輛編號}、{日期區間} 查詢行車資料", response = CarGPS.class)
    // 定義返回值意義
    @ApiResponses({
         @ApiResponse(code = 400, message = "服務器內部異常"),
         @ApiResponse(code = 401, message = "Unauthorized"),
         @ApiResponse(code = 402, message = "Forbidden"),
         @ApiResponse(code = 404, message = "Not Found"),
         @ApiResponse(code = 500, message = "權限不足")})
    @ApiImplicitParams({
        @ApiImplicitParam(name ="driver_id",value = "車輛編號",dataType = "int",paramType = "path",required = true),
        @ApiImplicitParam(name ="params",value = "查詢參數",dataType = "Params",required = true)
        })
    @ResponseBody
    public List<CarGPS> queryByDriverID(@PathVariable("driver_id") int carDriverID,@RequestBody Params params){
      log.info(LogUtil.concat("API","queryByDriverID"));
      String sDateStr = params.getSdate();
      String eDateStr = params.getEdate();
      long sDate = DateUtil.tranSlateDateStrToLong(sDateStr);
      long eDate  = DateUtil.tranSlateDateStrToLong(eDateStr);
      return iCarGPSService.listCarGPS(carDriverID, sDate, eDate);
    }
    
    @RequestMapping(value = "/cargps/{driver_id}/rawdata/add", method = {RequestMethod.POST}, produces={"application/json;charset=UTF-8","application/json;charset=UTF-8"})
    @ApiOperation(value = "新增行車資料", response = String.class)
    // 定義返回值意義
    @ApiResponses({
         @ApiResponse(code = 400, message = "服務器內部異常"),
         @ApiResponse(code = 401, message = "Unauthorized"),
         @ApiResponse(code = 402, message = "Forbidden"),
         @ApiResponse(code = 404, message = "Not Found"),
         @ApiResponse(code = 500, message = "權限不足")})
    @ApiImplicitParams({
        @ApiImplicitParam(name ="driver_id",value = "車輛編號",dataType = "int",paramType = "path",required = true),
        @ApiImplicitParam(name ="carGPS"  ,value = "查詢參數",dataType = "CarGPS",required = true)
        })
    @ResponseBody
    public String addCarGPS(@PathVariable("driver_id") int carDriverID,@RequestBody CarGPS carGPS){
        log.info(LogUtil.concat("API","addCarGPS"));
        iCarGPSService.saveCarGPS(carGPS);
        return APIUtil.getDefineMsg("1000");
    }
}




[參考資料]

這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

留言

這個網誌中的熱門文章

IoT|硬體|樹莓派|外接麥克風及喇叭設置

成長|語文|學習-英文 持續更新!

IoT|硬體|通訊|Arduino 使用 SoftwareSerial Library 與電腦通訊