接口测试工具Postman和接口文档Swagger了解

本文介绍如何使用Postman进行接口测试,以及如何通过Swagger自动生成接口文档,包括Swagger的配置和使用,以及如何在网关配置中整合多个模块的Swagger文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接口测试工具Postman

什么是Postman

写完以后,前端以后不是我们写,就算是我们写也应该先测试好接口,才写前端。所以要先测试,对于get请求可以使用浏览器地址访问,但是其他请求就不行。需要一些接口测试工具postman就是其中的一个,接口来我们就使用它来测试我们的登录接口
下载API路径(https://www.getpostman.com/)

使用

在这里插入图片描述

接口文档Swagger

在这里插入图片描述只需要在你的接口的项目中做一点配置:
导入swagger的依赖和一点配置,就可以通过浏览器访问接口

使用
1.导jar包
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
2.定义配置类
@Configuration //用于定义配置类
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.itsource.aigou.controller"))//扫描接口的包路径
                //包:就是自己接口的包路径
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("商品系统api")//接口文档名字
                .description("商品系统接口文档说明") //说明
                .contact(new Contact("wbtest", "", "wenbing@itsource.cn"))//邮件
                .version("1.0")// 版本
                .build();
    }
}

在这里插入图片描述

3.访问本项目地址:http://127.0.0.1:8001/swagger-ui.html
网关配置

前端开发时查询Swagger要记住指定的端口号,一旦开发模块过得就很麻烦,如果用网关访问的话只需要记住网关的端口,就方便开发,
注意:网关的swagger配置只是集合一下单个模块的swagger文档,所以每个接口都要进行以上配置

1.导jar包
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
2.定义配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration //定义配置类
@EnableSwagger2
public class SwaggerConfig {

    @Bean //定义一个bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("分布式购物系统")
                .description("购物系统接口文档说明")
                .termsOfServiceUrl("http://localhost:8081")
                .contact(new Contact("wbtest", "", "wenbing@itsoruce.cn"))
                .version("1.0")
                .build();
    }
}
3.yml配置
server:
  port: 9527
spring:
  application:
    name: MICROSERVICE-ZUUL-GATEWAY
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka
  instance:
    instance-id: gateway-9527.com
    prefer-ip-address: true #显示ip
zuul:
  routes:
    #========================== 通过网关zuul访问不同的模块 =====================
    myUser.serviceId: microservice-user-dev #这是调用满足条件的服务名,注意要小写MICROSERVICE-USER-DEV
    myUser.path: /user/** #这是所有路径前的通配
    #======================================================================
    myProduct.serviceId: aigou-product #这是调用满足条件的服务名,注意要小写
    myProduct.path: /product/** #这是所有路径前的通配
    #======================================================================
  ignored-services: "*" #用*来通配符,忽略从9527端口通过服务名来调用
  prefix: "/services" #这是所有路径的前缀
4.创建一个类实现SwaggerResourcesProvider
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList<>();
        //aigou网关前缀+“/”+user网关路径+"/"+swagger的路径 
        //以后增加了接口就在这配置就ok
        resources.add(swaggerResource("用户系统", "/aigou/user/v2/api-docs", "2.0"));
        resources.add(swaggerResource("用户系统2", "/aigou/product/v2/api-docs", "2.0"));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}
5.访问 http://127.0.0.1:9527/swagger-ui.html

在这里插入图片描述

### 如何配置 Swagger 中的 Available Authorizations 字段 在使用 Swagger 进行 API 文档管理时,`Available authorizations` 是用于指定授权方式的一个重要部分。它允许开发者定义哪些请求需要经过身份验证,并指明具体的认证机制。 #### 1. 配置 Authorization 的基本概念 Swagger 提供了一种灵活的方式来处理 API 授权问题。通常情况下,可以通过 `@ApiImplicitParams` `@ApiOperation` 注解来实现对特定接口的权限控制[^1]。而在全局范围内,则可以在 Swagger 配置类中完成更广泛的设置。 对于 `availableAuthorizations` 字段的具体填写方法,主要涉及以下几个方面: - **Authorization 类型**: 定义使用的授权协议(如 OAuth2 或者 Basic Auth)。 - **Token URL**: 如果采用的是 OAuth2 流程,那么此字段应指向获取 token 所需的服务端地址。 - **Scopes (作用域)**: 描述客户端申请令牌时所声明的作用范围。 #### 2. Spring Boot 整合 Swagger 并启用 Authorization 功能 下面是一个关于如何在 Spring Boot 应用程序里集成 Swagger3 及其授权功能的例子[^2]: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiKey; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example")) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList(new ApiKey("Bearer Token", "Authorization", "header"))); } } ``` 上述代码片段展示了怎样创建一个名为 `api()` 的 Bean 来初始化 Swagger UI 页面上的显示内容。特别注意 `.securitySchemes(...)` 方法调用的部分——这里我们添加了一个基于 HTTP Header 的安全方案实例 (`ApiKey`) ,它的名称设为 `"Bearer Token"` , 参数名则被命名为 `"Authorization"` 。这一步骤实际上就是告诉前端界面,在发送任何受保护资源之前,请先附加有效的 Bearer Token 到请求头当中去。 另外还需要调整 Web Security 设置以便让未登录状态下也能正常加载 swagger-ui.html 资源文件: ```java @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("/swagger-ui/**","/v3/api-docs/**").permitAll() .anyRequest().authenticated(); } ``` 以上两处改动共同构成了完整的解决方案框架结构图景. #### 3. 使用 Postman 或浏览器测试已部署服务 当完成了服务器端的相关准备工作之后, 就可以借助工具像 Postman 或者直接利用现代网络浏览器访问目标站点并尝试提交带有所谓 Access Tokens 请求了.[^3] 假设现在有一个 RESTful Service `/brands`, 我们希望只有持有合法凭证的人才可以读取全部品牌列表数据项. 此时应该按照如下流程操作: 1. 启动应用程序; 2. 登录成功后得到返回的有效期较短的一次性密钥(Token); 3. 把刚才拿到手的那个字符串复制粘贴到相应位置作为 value 值传入即可(记得加上前缀 word 'Bearer '); 4. 点击 Execute 按钮发起 GET 请求查看结果集. --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值