使用Swagger展示Restful服務的API

Swagger項目是一個可以將Restful服務的接口api doc可視化的工具,而且提供了在線調試api的功能,對于開發的Restful服務非常友好,因此可以將其集成到項目中來。

這里通過spring initializer創建一個結構簡單的spring boot程序,來展示Swagger的使用, 完整的項目示例參見

  • 創建一個spring boot web應用,導入webjpa, h2test等模塊。

  • 引入maven依賴

<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>
    <version>2.9.2</version>
</dependency>

  • 以一個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<Person> 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
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容