Java【Java开发集成 Swagger UI生成可视图的API文档(详细图解)】

目前几乎所有的开放平台都是把API以文档的形式放在网站上,如下:

不知道有没有开发人员和我一样,有时对一些API说明的理解比较模糊,总想着能直接验证一下自己的理解就好了,而不是需要去项目写测试代码来验证自己的想法。即API文档应具备直接执行能力。 Swagger就是这样的一个利器,其实,Swagger本身的目标比上面描述的要大很多:“Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. ”。但是,本文中只想聊聊如何通过Swagger为已有项目的生成具备执行能力的样式化API文档。 
为已存在的项目添加Swagger(以DropWizard为例)

首先,为项目引入Swagger依赖包

Gradle代码

-> 'com.wordnik:swagger-jaxrs_2.9.1:1.3.0' 
然后,把Swagger加入DropWizard的Service中:

Java代码 
private void initSwaggerConfig(Environment environment) { 
        // Swagger Resource 
        environment.addResource(new ApiListingResourceJSON()); 

        // Swagger providers 
        environment.addProvider(new ApiDeclarationProvider()); 
        environment.addProvider(new ResourceListingProvider()); 

        // Swagger Scanner, which finds all the resources for @Api Annotations 
        ScannerFactory.setScanner(new DefaultJaxrsScanner()); 

        // Add the reader, which scans the resources and extracts the resource information 
        ClassReaders.setReader(new DefaultJaxrsApiReader()); 

        //Config API information. this information will show on the Swagger UI page 
        SwaggerConfig config = ConfigFactory.config(); 
        config.setApiVersion("0.1"); 
        config.setApiPath("/api/api-docs"); //Swagger UI 默认把API信息显示在base_path/api-docs下 
        config.setBasePath(" http://localhost:9090/api "); 
        config.setInfo(Option.apply(new ApiInfo("DropWizard Demo Swagger UI", 
                "This is just a demo to show how to integrate Swagger UI with a dropwizard project.", 
                null, 
                "xianlinbox@gmail.com ", 
                null, 
                null))); 
    }
接着,给开放API的Resource类加上API Annotation,这样上一步配置的Scanner就能够扫描到该Resource开放的API了。

Java代码 
@Path("/helloWorld") 
@Api(value = "/helloWorld", description = "Greeting API", position = 1) 
@Produces(APPLICATION_JSON) 
public class HelloWorldResource { 
    private final String template; 
    private final String defaultName; 
    private final AtomicLong counter; 

    public HelloWorldResource(String template, String defaultName) { 
        this.template = template; 
        this.defaultName = defaultName; 
        this.counter = new AtomicLong(); 
    } 

    @GET 
    @Path("/{name}") 
    @ApiOperation(value = "Greeting by Name", 
            notes = "Say hello to the people", 
            response = SayingRepresentation.class, 
            position = 0) 
    @ApiResponses(value = { 
            @ApiResponse(code = 400, message = "No Name Provided") 
    }) 
    @Produces(APPLICATION_JSON) 
    @Timed 
    public SayingRepresentation sayHello(@ApiParam(value = "name for greeting", required = true) @PathParam("name") String name) { 
        return new SayingRepresentation(counter.incrementAndGet(), String.format(template, name != null ? name : defaultName)) 
                ; 
    } 
}
在Swagger Annotation中:

@API表示一个开放的API,可以通过description简要描述该API的功能。

在一个@API下,可有多个@ApiOperation,表示针对该API的CRUD操作。在ApiOperation Annotation中可以通过value,notes描述该操作的作用,response描述正常情况下该请求的返回对象类型。

在一个ApiOperation下,可以通过ApiResponses描述该API操作可能出现的异常情况。

@ApiParam用于描述该API操作接受的参数类型
再接着,为项目的Model对象添加Swagger Annotation,这样Swagger Scanner可以获取更多关于Model对象的信息。

Java代码 收藏代码

@ApiModel(value = "A SayingRepresentation is a representation of greeting")

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)

public class SayingRepresentation {

private long id;

@ApiModelProperty(value = "greeting content", required = true)

private String content; 
public SayingRepresentation(long id, String content) { 
    this.id = id; 
    this.content = content; 

public long getId() { 
    return id; 

public String getContent() { 
    return content; 
}
通过上面的步骤,项目已经具备了提供Swagger格式的API信息的能力,接下来,我们把这些信息和Swagger UI集成,以非常美观,实用的方式把这些API信息展示出来。 
和Swagger UI的集成

首先,从github( https://github.com/wordnik/swagger-ui)上下载Swagger-UI, 把该项目dist目录下的内容拷贝到项目的resources的目录assets下。 



然后,修改index.html, 把Swagger UI对象中的URL替换为自己的API路径。

Javascript代码 
window.swaggerUi = new SwaggerUi({ 
     url: "/api/api-docs", 
     dom_id: "swagger-ui-container",
最后,为了能访问到该页面,还需要在Service的Initialize方法中,添加AssetsBundle,

Java代码 
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) { 
        //指定配置文件的名字 
        bootstrap.setName("helloWorld"); 
        bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html")); 
    }
最后的效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值