swagger 介绍及两种使用方法

一:swagger是什么?

1、是一款让你更好的书写API文档规范且完整的框架。

2、提供描述、生产、消费和可视化RESTful Web Service。

3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。

方法一:使用第三方依赖(最简单的方法)

1、在pom.xml文件中添加第三方swagger依赖()

	<dependency>
		<groupId>com.spring4all</groupId>
		<artifactId>swagger-spring-boot-starter</artifactId>
		<version>1.7.0.RELEASE</version>
	</dependency>

2、在Spring Boot项目的启动类上添加@EnableSwagger2Doc注解,就可以直接使用啦。
3、https://github.com/SpringForAll/spring-boot-starter-swagger这是GitHub上这个swagger依赖实现的项目,里面有详细的讲解。

方法二:使用官方依赖

1、在pom.xml文件中添加swagger相关依赖
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。
2、swagger的configuration

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.yss.ms.admin"))
                    .paths(PathSelectors.any())
                    .build();
        }

        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台 APIs")
                    .description("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台")
                    .termsOfServiceUrl("http://192.168.1.198:10070/platformgroup/ms-admin")
                    .contact("程序猿")
                    .version("1.0")
                    .build();
        }

    }

三、具体使用

1、在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);
2、设定访问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";
    }
}

四:swagger的常用API

1、api标记

Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:

@Api(value = "/user", description = "Operations about user")

在这里插入图片描述

2、ApiOperation标记

ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:

@ApiOperation(
          value = "Find purchase order by ID",
          notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
          response = Order,
          tags = {"Pet Store"})

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V8AEIZ2l-1609508640724)(http://ozpb6wow8.bkt.clouddn.com/22.png)]

3、ApiParam标记

ApiParam请求属性,使用方式:

public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true)  User user)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5veQGqo7-1609508640725)(http://ozpb6wow8.bkt.clouddn.com/3.png)]

4、ApiResponse

ApiResponse:响应配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6nd1sH5D-1609508640729)(http://ozpb6wow8.bkt.clouddn.com/44.png)]

5、ApiResponses

ApiResponses:响应集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SNlJ6vSI-1609508640730)(http://ozpb6wow8.bkt.clouddn.com/5.png)]

6、ResponseHeader

响应头设置,使用方法
@ResponseHeader(name="head1",description="response head conf")
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NDXgB4JA-1609508640731)(http://ozpb6wow8.bkt.clouddn.com/6.png)]

  • 90
    点赞
  • 661
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
Swagger是一个API文档工具,它提供了API管理、测试和访问等功能。在Python中,有几个相关的包可以使用Swagger,如connexion、flasgger、flask-swagger和Flask-RESTPlus等。其中,flasgger是一个与Python web服务框架Flask高度集成的工具,它自带前端页面,无需安装其他依赖。 配置Swagger的方式有两种,一种是使用配置文件,另一种是在代码中进行全局配置。在配置文件方式中,你需要将注释放入api_get.yml文件中,并使用装饰器@swag_from来引用该文件。可以通过以下代码来实现: ```python from flask import Flask import random from flasgger import Swagger, swag_from app = Flask(__name__) Swagger(app) @app.route('/api/<string:language>/', methods=['GET']) @swag_from("api_get.yml") def index(language): # your code here app.run(debug=True) ``` 而在全局配置方式中,你可以使用Swagger的config参数和template参数来进行配置,如下所示: ```python from flask import Flask from flasgger import Swagger app = Flask(__name__) swagger_config = { "headers": [], "specs": [ { "endpoint": 'apispec_2', "route": '/apispecification.json', "rule_filter": lambda rule: True, "model_filter": lambda tag: True, } ], "static_url_path": "/flasgger_static", "swagger_ui": True, "specs_route": "/doc/" } template_config = { "info": { "title": "Sample API", "description": "This is a sample API", "version": "1.0.0" } } Swagger(app, template=template_config, config=swagger_config) app.run(debug=True) ``` 以上是Python中使用Swagger配置的简要介绍。你可以根据实际需求进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值