Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >使用swagger作为restful api的doc文档生成

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

作者头像
Ryan-Miao
发布于 2018-03-14 02:32:00
发布于 2018-03-14 02:32:00
2.4K00
代码可运行
举报
文章被收录于专栏:Ryan MiaoRyan Miao
运行总次数:0
代码可运行

初衷

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

swagger介绍

首先,官网这样写的:

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

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

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

效果为先,最终展示doc界面,也可以设置为中文:

在dropwizard中使用

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

在spring-boot中使用

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

github sample源码

配置

1.需要依赖两个包:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
        <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接口位置。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@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 也可以换成别的条件,比如:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }
3.在API上做一些声明
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//本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);

案例:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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中声明:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
springfox.documentation.swagger.v2.path: /api-docs

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

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

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Controller
public class HomeController {

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

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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下面的文件拷贝出来,然后修改请求数据方式即可。

6. 设置在生产环境关闭swagger

具体参考 http://www.cnblogs.com/woshimrf/p/disable-swagger.html

参考:

1.swagger官网:http://swagger.io/ 2.github: https://github.com/swagger-api/swagger-codegen/blob/master/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java 3.后续阅读文章:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
微服务RESTful接口文档生成神器Swagger初探
在微服务构建的过程中,你也许发现写的那些restful风格的接口需要编写文档。 文档一般包括要输入哪些参数,哪些参数是必填的,哪些是选填的。还有返回结果的格式以及结果示例。 也许你可以通过在git上写markdown文档来做这些事情。 但每个接口对应的文档地址这些对应关系你又需要关心。 通过swagger,这一切你都不需要做了。 在你编写自己的restful接口的时候,只需要添加一些annotation就可为你自动的生成接口文档。你上面的那些内容都为你自动生成。 甚至连简单的功能测试表单都为你做好了。 总
ImportSource
2018/04/03
1.1K0
微服务RESTful接口文档生成神器Swagger初探
SpringBoot非官方教程 | 第十一篇:springboot集成swagger2,构建优雅的Restful API
方志朋
2017/12/29
9180
SpringBoot非官方教程 | 第十一篇:springboot集成swagger2,构建优雅的Restful API
Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件
Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件
芥末鱿鱼
2020/09/22
2K0
Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件
SpirngBoot整合Swagger
由于Spring Boot能够快速开发、便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API。而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。
框架师
2021/03/05
1.2K0
使用Swagger生成Spring Boot微服务API文档
springfox是产生API文档,而swagger-ui 则是RestAPI的界面。 创建一个RestController ,定义API:
lyb-geek
2018/09/27
1.4K0
SpringCloud Alibaba 实战教程13-gateway网关聚合swagger
一、项目整合整合swagger 1.1引入pom文件 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <ve
gang_luo
2021/02/22
1.7K0
SpringCloud Alibaba 实战教程13-gateway网关聚合swagger
SpringBoot 实战 | 集成 Swagger2 构建强大的 RESTful API 文档
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
JavaFish
2019/10/17
7370
Spring boot整合Springfox在线生成restful的api doc
Springfox基于Swagger,能更方便的集成到spring boot 中,Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。Swagger的目标是对REST API定义一个标准的和语言无关的接口,可让人和计算机无需访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过Swagger进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger消除了调用服务时可能会有的猜测。
kl博主
2023/11/18
1.2K0
Spring boot整合Springfox在线生成restful的api doc
补习系列-springboot restful实战
摘自百科的定义:REST即表述性状态转移(英文:Representational State Transfer,简称REST) 是Roy Fielding博士(HTTP规范主要贡献者)在2000年的论文中提出来的一种软件架构风格。 是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。
美码师
2018/08/27
7470
补习系列-springboot restful实战
SpringBoot整合Swagger2「建议收藏」
Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。
全栈程序员站长
2022/08/04
3940
SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
整合到Spring Boot中,构建强大RESTful API文档。省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试功能来调试RESTful API。
知了一笑
2019/07/19
9660
SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
SpringBoot使用Swagger2实现Restful API
很多时候,我们需要创建一个接口项目用来数据调转,其中不包含任何业务逻辑,比如我们公司。这时我们就需要实现一个具有Restful API的接口项目。 本文介绍springboot使用swagger2实现
dalaoyang
2018/04/28
1.1K0
SpringBoot使用Swagger2实现Restful API
Swagger详细了解一下(长文谨慎阅读)
Swagger 是最流行的 API 开发工具,它遵循 OpenAPI Specification(OpenAPI 规范,也简称 OAS)。 Swagger 可以贯穿于整个 API 生态,如 API 的设计、编写 API 文档、测试和部署。 Swagger 是一种通用的,和编程语言无关的 API 描述规范。
IT苦逼一枚
2020/04/27
32.8K0
Spring Boot整合Swagger2搭建Restful API在线文档
目标:Spring Boot整合Swagger2 工具:IDEA--2020.1 学习目标:框架工具集成 本次学习的工程下载链接放到文本最后面 注意:本次项目基于springboot集成Mybatis基础之上的
背雷管的小青年
2020/06/08
7630
Spring Boot整合Swagger2搭建Restful API在线文档
原 JAVA懒开发:整合swagger对测
swagger 什么是swagger        swagger中文“拽”的意思。它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试。另外swagger很容易构建restful风格的api,简单优雅帅气,正如它的名字。 添加Swagger2依赖 <!-- swagger2与swagger-ui同一版本 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swag
kinbug [进阶者]
2018/06/13
1.3K0
SpirngBoot之整合Swagger2
swagger,中文“拽”的意思。它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅, 而且还提供了在线文档的测试。另外swagger很容易构建restful风格的api。
用户1195962
2018/08/02
5400
SpirngBoot之整合Swagger2
springboot (九) Swagger2实现Restful API
springboot使用swagger2实现Restful API。 本项目使用mysql+jpa+swagger2。 首先pom中加入swagger2,代码如下: <?xml version="1.
IT架构圈
2018/06/01
9290
SpringBoot整合Swagger
上一篇《简单搭建SpringBoot项目》讲了简单的搭建SpringBoot 项目,而 SpringBoot 和 Swagger-ui 搭配在持续交付的前后端开发中意义重大,Swagger 规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,对调用方而言非常直观,接口也可以点击try it out!按钮 进行调试,在实际开发中大大增加了开发效率。点击可了解更多 swagger 相关信息swagger-ui官网
java之旅
2020/01/03
6920
Spring Boot从零入门6_Swagger2生成生产环境中REST API文档
在如今前后端分离开发的模式下,前端调用后端提供的API去实现数据的展示或者相关的数据操作,保证及时更新和完整的REST API文档将会大大地提高两边的工作效率,减少不必要的沟通成本。本文采用的Swagger2就是一个当前流行的通过少量的注解就可以生成漂亮的API文档工具,且在生成的在线文档中提供类似POSTMAN直接调试能力,不仅仅是静态的文档。接下来将会利用这个工具与Spring Boot项目结合,最终生成我们上一篇文章中所涉及到的REST API文档。
别打名名
2019/12/23
2.3K0
Spring Boot从零入门6_Swagger2生成生产环境中REST API文档
搭建单体SpringBoot项目 集成Swagger接口文档
浏览器访问 http://ip:port/swagger-ui/index.html
郭顺发
2023/07/07
4460
推荐阅读
相关推荐
微服务RESTful接口文档生成神器Swagger初探
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验