Swagger的使用

        在此前写接口的时候用的都是postman,包括前端也是通过postman进行查看接口的相关信息的,听说Swagger还挺好用的,可以自动生成接口文档,我就与项目整合在一起,发现还行(应前端的要求哈哈哈)

       接下来我来记录一下我项目整合的过程吧!我是SpringBoot整合Swagger2

      第一步导入相关的包

<!-- Swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<!-- END Swagger -->

     第二步:编写配置类

     

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(Environment environment){
        //设置要显示swagger的环境
        Profiles profile = Profiles.of("dev");
        //获取项目环境(判断是否处在自己设定的环境中)
        boolean flag = environment.acceptsProfiles(profile);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)//是否启动Swagger,如果是false,则Swagger不能在浏览器中访问
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.controller"))//RequestHandlerSelectors:配置要扫描接口的方式:此处是基于指定包
                .paths(PathSelectors.any())//过滤什么路径
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     *
     * <pre>
     *     我们可以配置多个bean,那么在显示地时候我们可以对接口进行分组
     *     尤其是多人开发的时候,根据每个人写的接口进行分组,比较好管理
     * <pre>
     * @author hejianfeng
     * @date 2020/2/29
     * @param
     * @return springfox.documentation.spring.web.plugins.Docket
     * <pre>
     * 修改记录
     * 版本号		修订日期		修改人		bug编号		修改内容
     * 1.0.0	  2020/2/29      何建锋		    		     新建
     * </pre>
     */
    @Bean
    public Docket docketOne(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("hejianfeng");
    }

    //只希望在生产环境中使用,发布的时候不使用
    //
    /**
     *
     * <pre>
     *     配置swagger信息
     * <pre>
     * @author 何建锋
     * @date 2020/2/29
     * @param
     * @return springfox.documentation.service.ApiInfo
     * <pre>
     * 修改记录
     * 版本号		修订日期		修改人		bug编号		修改内容
     * 1.0.0	  2020/2/29      何建锋		    		     新建
     * </pre>
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("我的API文档")
                .description("mall后台模块")
                .contact("macro")
                .version("1.0")
                .build();
    }

    private List<ApiKey> securitySchemes() {
        //设置请求头信息
        List<ApiKey> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }

    private List<SecurityContext> securityContexts() {
        //设置需要登录认证的路径
        List<SecurityContext> result = new ArrayList<>();
        result.add(getContextByPath("/brand/.*"));
        result.add(getContextByPath("/product/.*"));
        result.add(getContextByPath("/productCategory/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex){
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}

       第三步:在controller类中添加注解使用

      

Swagger是一个用于设计、构建和文档化RESTful Web服务的开源工具集。下面是一个简单的Swagger使用教程: 1. 安装Swagger:可以通过npm、pip等包管理工具安装Swagger相关的库和工具。例如,对于Node.js项目,可以使用以下命令安装swagger-jsdoc和swagger-ui-express: ```bash npm install swagger-jsdoc swagger-ui-express ``` 2. 编写Swagger注解:在你的API代码中,使用Swagger注解来描述API的信息、请求和响应参数等。以下是一个示例: ```javascript /** * @swagger * /api/users: * get: * summary: 获取所有用户 * description: 获取所有用户列表 * responses: * 200: * description: 成功获取用户列表 * schema: * type: array * items: * $ref: '#/definitions/User' */ ``` 在这个示例中,我们使用Swagger注解来描述一个GET请求,它可以获取所有用户的列表。 3. 生成Swagger文档:使用Swagger注解编写完API代码后,可以使用相应的工具将这些注解转换为Swagger文档。例如,对于Node.js项目,我们可以使用swagger-jsdoc库生成Swagger文档。在项目的入口文件中添加以下代码: ```javascript const swaggerJSDoc = require('swagger-jsdoc'); const swaggerUi = require('swagger-ui-express'); const options = { definition: { openapi: '3.0.0', info: { title: 'API文档', version: '1.0.0', }, }, apis: ['./path/to/api/controllers/*.js'], // API代码文件的路径 }; const swaggerSpec = swaggerJSDoc(options); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); ``` 这段代码将会在`/api-docs`路径下提供Swagger文档。 4. 查看Swagger文档:运行项目并访问`/api-docs`路径,你将会看到生成的Swagger文档。Swagger提供了一个交互式的UI界面,可以方便地查看API的信息、请求和响应参数等。 这只是一个简单的Swagger使用教程,你可以根据自己的项目需求进一步深入学习和使用Swagger
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值