使用swagger作为restful api的doc文档生成

简介:

初衷

记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情。也许多点,也许少点。甚至,接口总是需要适应新需求的,修改了,增加了,这份文档维护起来就很困难了。于是发现了swagger,自动生成文档的工具。

swagger介绍

首先,官网这样写的:

Swagger – The World's Most Popular Framework for APIs.

因为自强所以自信。swagger官方更新很给力,各种版本的更新都有。swagger会扫描配置的API文档格式自动生成一份json数据,而swagger官方也提供了ui来做通常的展示,当然也支持自定义ui的。不过对后端开发者来说,能用就可以了,官方就可以了。

最强的是,不仅展示API,而且可以调用访问,只要输入参数既可以try it out.

效果为先,最终展示doc界面,也可以设置为中文:
686418-20160914235935805-777612461.png

在dropwizard中使用

详细信息见另一篇在dropwizard中使用Swagger

在spring-boot中使用

以前总是看各种博客来配置,这次也不例外。百度了千篇一律却又各有细微的差别,甚至时间上、版本上各有不同。最终还是去看官方文档,终于发现了官方的sample。针对于各种option的操作完全在demo中了,所以clone照抄就可以用了。

github sample源码

配置

1.需要依赖两个包:


        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency>

第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。

2.swagger的configuration

需要特别注意的是swagger scan base package,这是扫描注解的配置,即你的API接口位置。


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.test.web.controllers";
    public static final String VERSION = "1.0.0";

    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger API")
                .description("This is to show api description")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .termsOfServiceUrl("")
                .version(VERSION)
                .contact(new Contact("","", "miaorf@outlook.com"))
                .build();
    }

    @Bean
    public Docket customImplementation(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .build()
                .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
                .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
                .apiInfo(apiInfo());
    }
}

当然,scan package 也可以换成别的条件,比如:

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }

3.在API上做一些声明

//本controller的功能描述
@Api(value = "pet", description = "the pet API")
public interface PetApi {

    //option的value的内容是这个method的描述,notes是详细描述,response是最终返回的json model。其他可以忽略
    @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = {
        @Authorization(value = "petstore_auth", scopes = {
            @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
            @AuthorizationScope(scope = "read:pets", description = "read your pets")
            })
    }, tags={ "pet", })

    //这里是显示你可能返回的http状态,以及原因。比如404 not found, 303 see other
    @ApiResponses(value = { 
        @ApiResponse(code = 405, message = "Invalid input", response = Void.class) })
    @RequestMapping(value = "/pet",
        produces = { "application/xml", "application/json" }, 
        consumes = { "application/json", "application/xml" },
        method = RequestMethod.POST)
    ResponseEntity<Void> addPet(
    //这里是针对每个参数的描述
    @ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);

案例:

package com.test.mybatis.web.controllers;

import com.test.mybatis.domain.entity.City;
import com.test.mybatis.domain.entity.Hotel;
import com.test.mybatis.domain.mapper.CityMapper;
import com.test.mybatis.domain.mapper.HotelMapper;
import com.test.mybatis.domain.model.common.BaseResponse;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by miaorf on 2016/9/10.
 */

@Api(value = "Test", description = "test the swagger API")
@RestController
public class TestController {

    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private HotelMapper hotelMapper;

    @ApiOperation(value = "get city by state", notes = "Get city by state", response = City.class)
    @ApiResponses(value = {@ApiResponse(code = 405, message = "Invalid input", response = City.class) })
    @RequestMapping(value = "/city", method = RequestMethod.GET)
    public ResponseEntity<BaseResponse<City>>  getCityByState(
            @ApiParam(value = "The id of the city" ,required=true ) @RequestParam String state){

        City city = cityMapper.findByState(state);
        if (city!=null){
            BaseResponse response = new BaseResponse(city,true,null);
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation(value = "save city", notes = "", response = City.class)
    @RequestMapping(value = "/city", method = RequestMethod.POST)
    public ResponseEntity<BaseResponse<City>> saveCity(
            @ApiParam(value = "The id of the city" ,required=true ) @RequestBody City city){

        int save = cityMapper.save(city);
        if (save>0){
            BaseResponse response = new BaseResponse(city,true,null);
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation(value = "save hotel", notes = "", response = Hotel.class)
    @RequestMapping(value = "/hotel", method = RequestMethod.POST)
    public ResponseEntity<BaseResponse<Hotel>> saveHotel(
            @ApiParam(value = "hotel" ,required=true ) @RequestBody Hotel hotel){

        int save = hotelMapper.save(hotel);
        if (save>0){
            BaseResponse response = new BaseResponse(hotel,true,null);
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation(value = "get the hotel", notes = "get the hotel by the city id", response = Hotel.class)
    @RequestMapping(value = "/hotel", method = RequestMethod.GET)
    public ResponseEntity<BaseResponse<Hotel>> getHotel(
            @ApiParam(value = "the hotel id" ,required=true ) @RequestParam Long cid){

        List<Hotel> hotels = hotelMapper.selectByCityId(cid);
        return new ResponseEntity<>(new BaseResponse(hotels,true,null), HttpStatus.OK);
    }

    @ApiOperation(value = "update the hotel", notes = "update the hotel", response = Hotel.class)
    @RequestMapping(value = "/hotel", method = RequestMethod.PUT)
    public ResponseEntity<BaseResponse<Hotel>> updateHotel(
            @ApiParam(value = "the hotel" ,required=true ) @RequestBody Hotel hotel){

        int result = hotelMapper.update(hotel);
        return new ResponseEntity<>(new BaseResponse(result,true,null), HttpStatus.OK);
    }


    @ApiOperation(value = "delete the  hotel", notes = "delete the hotel by the hotel id", response = City.class)
    @RequestMapping(value = "/hotel", method = RequestMethod.DELETE)
    public ResponseEntity<BaseResponse<Hotel>> deleteHotel(
            @ApiParam(value = "the hotel id" ,required=true ) @RequestParam Long htid){

        int result = hotelMapper.delete(htid);
        return new ResponseEntity<>(new BaseResponse(result,true,null), HttpStatus.OK);
    }


}

4.设定访问API doc的路由

在配置文件中,application.yml中声明:

springfox.documentation.swagger.v2.path: /api-docs

这个path就是json的访问request mapping.可以自定义,防止与自身代码冲突。

API doc的显示路由是:http://localhost:8080/swagger-ui.html

如果项目是一个webservice,通常设定home / 指向这里:

@Controller
public class HomeController {

    @RequestMapping(value = "/swagger")
    public String index() {
        System.out.println("swagger-ui.html");
        return "redirect:swagger-ui.html";
    }
}

5.访问

就是上面的了。但是,注意到安全问题就会感觉困扰。首先,该接口请求有几个:

http://localhost:8080/swagger-resources/configuration/ui
http://localhost:8080/swagger-resources
http://localhost:8080/api-docs
http://localhost:8080/swagger-resources/configuration/security

除却自定义的url,还有2个ui显示的API和一个安全问题的API。关于安全问题的配置还没去研究,但目前发现一个问题是在我的一个项目中,所有的url必须带有query htid=xxx,这是为了sso portal验证的时候需要。这样这个几个路由就不符合要求了。

如果不想去研究安全问题怎么解决,那么可以自定ui。只需要将ui下面的文件拷贝出来,然后修改请求数据方式即可。


本文转自Ryan.Miao博客园博客,原文链接:http://www.cnblogs.com/woshimrf/p/swagger.html,如需转载请自行联系原作者

相关文章
|
10天前
|
安全 Java API
RESTful API设计与实现:Java后台开发指南
【4月更文挑战第15天】本文介绍了如何使用Java开发RESTful API,重点是Spring Boot框架和Spring MVC。遵循无状态、统一接口、资源标识和JSON数据格式的设计原则,通过创建控制器处理HTTP请求,如示例中的用户管理操作。此外,文章还提及数据绑定、验证、异常处理和跨域支持。最后,提出了版本控制、安全性、文档测试以及限流和缓存的最佳实践,以确保API的稳定、安全和高效。
|
13天前
|
小程序 前端开发 API
小程序全栈开发中的RESTful API设计
【4月更文挑战第12天】本文探讨了小程序全栈开发中的RESTful API设计,旨在帮助开发者理解和掌握相关技术。RESTful API基于REST架构风格,利用HTTP协议进行数据交互,遵循URI、客户端-服务器架构、无状态通信、标准HTTP方法和资源表述等原则。在小程序开发中,通过资源建模、设计API接口、定义资源表述及实现接口,实现前后端高效分离,提升开发效率和代码质量。小程序前端利用微信API与后端交互,确保数据流通。掌握这些实践将优化小程序全栈开发。
|
22天前
|
前端开发 Java API
构建RESTful API:Java中的RESTful服务开发
【4月更文挑战第3天】本文介绍了在Java环境中构建RESTful API的重要性及方法。遵循REST原则,利用HTTP方法处理资源,实现CRUD操作。在Java中,常用框架如Spring MVC简化了RESTful服务开发,包括定义资源、设计表示层、实现CRUD、考虑安全性、文档和测试。通过Spring MVC示例展示了创建RESTful服务的步骤,强调了其在现代Web服务开发中的关键角色,有助于提升互操作性和用户体验。
构建RESTful API:Java中的RESTful服务开发
|
26天前
|
XML JSON 安全
谈谈你对RESTful API设计的理解和实践。
RESTful API是基于HTTP协议的接口设计,通过URI标识资源,利用GET、POST、PUT、DELETE等方法操作资源。设计注重无状态、一致性、分层、错误处理、版本控制、文档、安全和测试,确保易用、可扩展和安全。例如,`/users/{id}`用于用户管理,使用JSON或XML交换数据,提升系统互操作性和可维护性。
18 4
|
28天前
|
安全 API 开发者
构建高效可扩展的RESTful API服务
在数字化转型的浪潮中,构建一个高效、可扩展且易于维护的后端API服务是企业竞争力的关键。本文将深入探讨如何利用现代后端技术栈实现RESTful API服务的优化,包括代码结构设计、性能调优、安全性强化以及微服务架构的应用。我们将通过实践案例分析,揭示后端开发的最佳实践,帮助开发者提升系统的响应速度和处理能力,同时确保服务的高可用性和安全。
27 3
|
1月前
|
缓存 前端开发 API
构建高效可扩展的RESTful API:后端开发的最佳实践
【2月更文挑战第30天】 在现代Web应用和服务端架构中,RESTful API已成为连接前端与后端、实现服务间通信的重要接口。本文将探讨构建一个高效且可扩展的RESTful API的关键步骤和最佳实践,包括设计原则、性能优化、安全性考虑以及错误处理机制。通过这些实践,开发者可以确保API的健壮性、易用性和未来的可维护性。
|
1月前
|
API 开发者 UED
深入探讨RESTful API设计原则及最佳实践
在当今互联网时代,RESTful API已成为各种软件系统之间进行通信的重要方式。本文将从资源定义、URI设计、HTTP方法选择、状态码规范等方面深入探讨RESTful API设计的原则与最佳实践,帮助开发者更好地构建高效、健壮的API。
|
API
SenchaTouch 2.4 离线api文档下载
http://pan.baidu.com/s/1jG5THZK
886 0
|
16天前
|
缓存 前端开发 API
API接口封装系列
API(Application Programming Interface)接口封装是将系统内部的功能封装成可复用的程序接口并向外部提供,以便其他系统调用和使用这些功能,通过这种方式实现系统之间的通信和协作。下面将介绍API接口封装的一些关键步骤和注意事项。
|
23天前
|
监控 前端开发 JavaScript
实战篇:商品API接口在跨平台销售中的有效运用与案例解析
随着电子商务的蓬勃发展,企业为了扩大市场覆盖面,经常需要在多个在线平台上展示和销售产品。然而,手工管理多个平台的库存、价格、商品描述等信息既耗时又容易出错。商品API接口在这一背景下显得尤为重要,它能够帮助企业在不同的销售平台之间实现商品信息的高效同步和管理。本文将通过具体的淘宝API接口使用案例,展示如何在跨平台销售中有效利用商品API接口,以及如何通过代码实现数据的统一管理。