如何生成 swagger.json [英] How to generate swagger.json

查看:98
本文介绍了如何生成 swagger.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java spring boot 框架为我的项目创建 REST api,我正在使用springfox-swagger2 和 springfox-swagger-ui"来生成 swagger 文档.我可以使用 URL http://localhost:8080/swagger-ui.html.

I am using java spring boot framework to create REST api for my project and I am using "springfox-swagger2 and springfox-swagger-ui" for generating swagger documentation. I am able to see my documentation using the URL http://localhost:8080/swagger-ui.html.

我如何创建或生成 swagger.json/spec.json,文档不应与此应用程序一起使用,我们使用单独的应用程序来列出 API 文档.

How can I create or generate swagger.json / spec.json, The documentation should not be with this application, we are using a separate application for listing the API docs.

推荐答案

我用一个小技巧做到了这一点

I have done this with a small trick

我在我的家庭控制器测试用例的末尾添加了以下代码

I have added the following code in the end of my home controller test case

import org.springframework.boot.test.web.client.TestRestTemplate;

public class HomeControllerTest extends .... ...... {

@Autowired
private TestRestTemplate restTemplate;


@Test
public void testHome() throws Exception {
     //.......
     //... my home controller test code 
     //.....

    String swagger = this.restTemplate.getForObject("/v2/api-docs", String.class);

    this.writeFile("spec.json", swagger );
}

public void writeFile(String fileName, String content) {

    File theDir = new File("swagger");

    if (!theDir.exists()) {
        try{
            theDir.mkdir();
        } 
        catch(SecurityException se){ }        
    }

    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
        fw = new FileWriter("swagger/"+fileName);
        bw = new BufferedWriter(fw);
        bw.write(content);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
            if (fw != null)
                fw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}
}

我不知道这是否正确但它正在起作用:)

I don't know this is right way or not But it is working :)

依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency> 

这篇关于如何生成 swagger.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆