使用Swagger展示Restful服务的API

Swagger项目是一个可以将Restful服务的接口api doc可视化的工具,而且提供了在线调试api的功能,对于开发的Restful服务非常友好,因此可以将其集成到项目中来。

这里通过spring initializer创建一个结构简单的spring boot程序,来展示Swagger的使用, 完整的项目示例参见:

  • 创建一个spring boot web应用,导入webjpa, h2test等模块。

  • 引入maven依赖


    io.springfox
    springfox-swagger2
    2.9.2



    io.springfox
    springfox-swagger-ui
    2.9.2


  • 以一个Person模型的查询(query)为例,创建POJOPerson、数据访问ContactDao接口、服务ContactService接口、以及对应的Restful服务控制器Controller。其中,在Controller中暴露3个Rest服务接口:
@RestController
@RequestMapping("/")
public class ContactController {

    @Autowired
    private ContactService contactService;

    @GetMapping("/test")
    public String test() {
        return "hello world";
    }

    @GetMapping("/persons")
    public Iterable getAllPersons() {
        return contactService.getAllContacts();
    }

    @GetMapping("/getPersonById")
    public Person getPersonById(@RequestParam("id") int personId) {
        return contactService.getContactById(personId);
    }



  1. /test用来测试
  2. /persons查询所有Person对象
  3. getPersonById根据id来查询对应的Person
  • 配置Swagger

使用注解@EnableSwagger2来启用相关功能。


@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("io.github.ted005.swaggerdemo.controller"))
                .build();

    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

  • 运行查看api doc, 打开http://localhost:8080/swagger-ui.html,会列出提供的api接口。
Screenshot_2019-01-21 Swagger UI.png

而且,还可以对每一个接口进行测试(可能需要构造请求参数):

Screenshot_2019-01-21 Swagger UI(1).png

你可能感兴趣的:(使用Swagger展示Restful服务的API)