Swagger 這一個文章就夠了

Swagger 這一個文章就夠了

From:https://blog.csdn.net/crisschan

Swagger快速理解

Swagger:The Best APIs are Built with Swagger Tools。Swagger可以定義一個標準的RESTful風格的API,與語言無關,是一個API的規範。

Swagger官網:http://swagger.io

GitHub地址:https://github.com/swagger-api

這裏,提到Swagger就不得不說說Springfox,Springfox是一個開源的API Doc的框架, 它的前身是swagger-springmvc,可以將我們的Controller中的方法以文檔的形式展現。官方定義爲: Automated JSON API documentation for API's built with Spring。Swagger和SpringFox到底什麼關係呢?

    - Swagger Spec 是一個規範。
    - Swagger Api 是 Swagger Spec 規範 的一個實現,它支持 jax-rs, restlet, jersey 等等。
    - Springfox libraries 是 Swagger Spec 規範 的另一個實現,專注於 spring 生態系統。
    - Swagger.js and Swagger-ui 是 javascript 的客戶端庫,能消費該規範。
    - springfox-swagger-ui 僅僅是以一種方便的方式封裝了 swagger-ui ,使得 Spring 服務可以提供服務。

在官網的Tools菜單中,我們會方法裏面有很多工具或者系統的介紹。其中我們最常用的兩個工具一個是swagger editor、一個是swagger UI。

Swagger Edit

Swagger Edit主要是用來設計,描述API的工具,主要是提供給接口開發人員使用的。swagger editor 編譯完接口文檔之後呢,會形成一個文件。

Swagger UI

Swagger UI允許任何人 - 無論是您的開發團隊還是最終消費者 - 在沒有任何實現邏輯的情況下可視化和與API資源交互。 它是從您的OpenAPI規範自動生成的,其可視化文檔使後端實現和客戶端消費變得容易。

swagger-editor主要是編寫api接口文檔,但需要配合swagger-ui來查看,裏面的代碼格式爲yaml,但編輯後可以導出yml/json文件

Swagger Edit和Swagger UI 互補性存在

如果只是手動寫api文檔,人工查看那麼就做部署Swagger Edit和Swagger UI就可以了。

通過下面命令下載兩個項目:

    mkdir swagger 
    chmod 777 swagger
    cd swagger
    git clone https://github.com/swagger-api/swagger-editor.git
    git clone https://github.com/swagger-api/swagger-ui.git

PS: UI和Edit都是NodeJS的開發,一次需要先安裝Nodejs的運行環境。

    下載nodejs的安裝包,具體要去網站上查看最新版本
    wget https://nodejs.org/dist/v6.11.3/node-v6.11.3.tar.gz
    tar -zxvf node-v6.11.3.tar.gz
    mv node-v6.11.3 /user/local/node
    cd /usr/local/node
    ./configure
    make 
    make install
    node -v

先安裝http-server

    npm install -g http-server

-g表示全局

啓動ui和edit

    http-server –p 12321 swagger-editor
    http-server –p 12421 swagger-ui
    cd swagger-ui/dist
    vim index.html

進入index.html後,修改如下字段

    ...
    const ui = SwaggerUIBundle({
    //url: "http://petstore.swagger.io/v2/swagger.json",
    url: "http://127.0.0.1:12321/json/1.json",
    dom_id: '#swagger-ui',
    ...

然後保存後

打開瀏覽器:

    swaggerEdit : http://127.0.0.1:12321
    swaggerUI:http://127.0.0.1:12421/dist

Maven插件在原生工程裏面快速生產Json的api文件(轉自:https://blog.csdn.net/doctor_who2004/article/details/50816208)

在maven工程的pom文件中,放入如下插件:

    <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <configuration>
                        <charset>UTF-8</charset>
                        <docencoding>UTF-8</docencoding>
                        <failOnError>false</failOnError>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>com.github.kongchen</groupId>
                    <artifactId>swagger-maven-plugin</artifactId>
                    <configuration>
                        <apiSources>
                            <apiSource>
                                <springmvc>false</springmvc>
                                <locations>com.doctor.demo</locations>
                                <schemes>http,https</schemes>
                                <host>petstore.swagger.wordnik.com</host>
                                <basePath>/api</basePath>
                                <info>
                                    <title>Swagger Maven Plugin Sample</title>
                                    <version>v1</version>
                                    <description>This is a sample for swagger-maven-plugin</description>
                                    <termsOfService>
                                        http://www.github.com/kongchen/swagger-maven-plugin
                                    </termsOfService>
                                    <contact>
                                        <email>[email protected]</email>
                                        <name>Kong Chen</name>
                                        <url>http://kongch.com</url>
                                    </contact>
                                    <license>
                                        <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
                                        <name>Apache 2.0</name>
                                    </license>
                                </info>
                                Support classpath or file absolute path here. 1) classpath e.g: "classpath:/markdown.hbs", "classpath:/templates/hello.html" 2) file e.g: "${basedir}/src/main/resources/markdown.hbs", "${basedir}/src/main/resources/template/hello.html"
                                <templatePath>${basedir}/templates/strapdown.html.hbs</templatePath>
                                <outputPath>${basedir}/generated/document.html</outputPath>
                                <swaggerDirectory>generated/swagger-ui</swaggerDirectory>
                            </apiSource>
                        </apiSources>
                    </configuration>
                    <executions>
                        <execution>
                            <phase>compile</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>

Swagger和SpringMVC項目的整合(轉自:https://www.cnblogs.com/jtlgb/p/6734177.html)

引入依賴

    <!-- swagger-springmvc -->
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.3.11</version>
        </dependency>
        <!-- swagger-springmvc dependencies -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>15.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>classmate</artifactId>
            <version>1.1.0</version>
        </dependency>

Swagger配置

Swagger的配置實際上就是自定義一個Config類,通過java編碼的方式實現配置。代碼如下:

    import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
    import com.mangofactory.swagger.models.dto.ApiInfo;
    import com.mangofactory.swagger.plugin.EnableSwagger;
    import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    /**
    * Created by xiaohui on 2016/1/14.
    */
    @Configuration
    @EnableSwagger
    @EnableWebMvc
    public class SwaggerConfig {
        private SpringSwaggerConfig springSwaggerConfig;
        /**
        * Required to autowire SpringSwaggerConfig
        */
        @Autowired
        public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)
        {
            this.springSwaggerConfig = springSwaggerConfig;
        }
        /**
        * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
        * framework - allowing for multiple swagger groups i.e. same code base
        * multiple swagger resource listings.
        */
        @Bean
        public SwaggerSpringMvcPlugin customImplementation()
        {
            return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                    .apiInfo(apiInfo())
                    .includePatterns(".*?");
        }
        private ApiInfo apiInfo()
        {
            ApiInfo apiInfo = new ApiInfo(
                    "My Apps API Title",
                    "My Apps API Description",
                    "My Apps API terms of service",
                    "My Apps API Contact Email",
                    "My Apps API Licence Type",
                    "My Apps API License URL");
            return apiInfo;
        }
    }

在springmvc的配置文件中加入以下配置即可。

    <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

  到目前爲止,我們已經完成了對所有接口方法的掃描解析功能,那解析得到什麼內容呢?這需要我們自定義,自定義操作的對象就是接口方法。先看段代碼:

    /**
    * 根據用戶名獲取用戶對象
    * @param name
    * @return
    */
    @RequestMapping(value="/name/{name}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根據用戶名獲取用戶對象", httpMethod = "GET", response = ApiResult.class, notes = "根據用戶名獲取用戶對象")
    public ApiResult getUserByName(@ApiParam(required = true, name = "name", value = "用戶名") @PathVariable String name) throws Exception{
        UcUser ucUser = ucUserManager.getUserByName(name);
        if(ucUser != null) {
            ApiResult<UcUser> result = new ApiResult<UcUser>();
            result.setCode(ResultCode.SUCCESS.getCode());
            result.setData(ucUser);
            return result;
        } else {
            throw new BusinessException("根據{name="   name   "}獲取不到UcUser對象");
        }
    }

上述代碼是Controller中的一個方法,@ApiOperation註解對這個方法進行了說明,@ApiParam註解對方法參數進行了說明。關於這兩個註解的使用,可以參看源碼。這樣子,Swagger就可以掃描接口方法,得到我們自定義的接口說明內容。

說明:其中@ApiOperation和@ApiParam爲添加的API相關注解,個參數說明如下:@ApiOperation(value = “接口說明”, httpMethod = “接口請求方式”, response = “接口返回參數類型”, notes = “接口發佈說明”;其他參數可參考源碼;@ApiParam(required = “是否必須參數”, name = “參數名稱”, value = “參數具體描述”

Swagger-UI配置

Swagger掃描解析得到的是一個json文檔,對於用戶不太友好。下面介紹swagger-ui,它能夠友好的展示解析得到的接口說明內容。

從https://github.com/swagger-api/swagger-ui 獲取3.0版本以下,2.0版本以上。其所有的 dist 目錄下東西放到需要集成的項目裏,本文放入 src/main/webapp/WEB-INF/swagger/ 目錄下。

修改swagger/index.html文件,默認是從連接http://petstore.swagger.io/v2/swagger.json獲取 API 的 JSON,這裏需要將url值修改爲http://{ip}:{port}/{projectName}/api-docs的形式,{}中的值根據自身情況填寫。比如我的url值爲:http://localhost:8083/arrow-api/api-docs

因爲swagger-ui項目都是靜態資源,restful形式的攔截方法會將靜態資源進行攔截處理,所以在springmvc配置文件中需要配置對靜態文件的處理方式。

    //所有swagger目錄的訪問,直接訪問location指定的目錄
    <mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger/"/>

 OK!大功告成,打開瀏覽器直接訪問swagger目錄下的index.html文件,即可看到接口文檔說明了

參考:

https://blog.csdn.net/kinginblue/article/details/78513029https://www.jianshu.com/p/52acab692a79https://blog.csdn.net/doctor_who2004/article/details/50816208https://www.cnblogs.com/jtlgb/p/6734177.html關注我,關注測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章