swagger-codegen自動生成代碼工具的介紹與使用

1、Swagger Codegen簡介

Swagger Codegen是一個開源的代碼生成器,根據Swagger定義的RESTful API能夠自動創建服務端和客戶端的鏈接。Swagger Codegen的源碼能夠在Github上找到。javascript

GitHub: https://github.com/swagger-api/swagger-codegenphp

2、Swagger Codegen安裝

首先機器上須要安裝jdk,具體Java, version 7 or higher,而後在這裏(https://oss.sonatype.org/content/repositories/releases/io/swagger/)找到須要的Swagger Codegen版原本安裝,不過官方是推薦最新版本。html

 

只要下載一個clijar文件就能夠了,例如, swagger-codegen-cli-2.2.1.jar(已共享到QQ羣文件:301343109)。也能夠直接在命令行裏下載,例如java

Wget https://oss.sonatype.org/content/repositories/releases/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar

 

下載好了,運行node

java -jar swagger-codegen-cli-2.2.1.jar

 

根據返回結果能夠看到Swagger Codegen支持的語言有不少: [android, aspnet5, async-scala, cwiki, csharp, cpprest, dart, flash, python-flask, go, groovy, java, jaxrs, jaxrs-cxf, jaxrs-resteasy, jaxrs-spec, inflector, javascript, javascript-closure-angular, jmeter, nancyfx, nodejs-server, objc, perl, php, python, qt5cpp, ruby, scala, scalatra, silex-PHP, sinatra, rails5, slim, spring, dynamic-html, html, html2, swagger, swagger-yaml, swift, tizen, typescript-angular2, typescript-angular, typescript-node, typescript-fetch, akka-scala, CsharpDotNet2, clojure, haskell, lumen, go-server]python

3、Swagger Codegen的使用

查看Swagger Codegen的幫助信息

java -jar swagger-codegen-cli-2.2.1.jar help generate

查看Swagger Codegen支持的具體某個語言的使用幫助,拿java舉例

java -jar swagger-codegen-cli-2.2.1.jar config-help -l java
C:\Users\Administrator\Documents\swagger-coden>java -jar swagger-codegen-cli-2.3.0.jar help generate
NAME
        swagger-codegen-cli generate - Generate code with chosen lang

SYNOPSIS
        swagger-codegen-cli generate
                [(-a <authorization> | --auth <authorization>)]
                [--additional-properties <additional properties>...]
                [--api-package <api package>] [--artifact-id <artifact id>]
                [--artifact-version <artifact version>]
                [(-c <configuration file> | --config <configuration file>)]
                [-D <system properties>...] [--git-repo-id <git repo id>]
                [--git-user-id <git user id>] [--group-id <group id>]
                [--http-user-agent <http user agent>]
                (-i <spec file> | --input-spec <spec file>)
                [--ignore-file-override <ignore file override location>]
                [--import-mappings <import mappings>...]
                [--instantiation-types <instantiation types>...]
                [--invoker-package <invoker package>]
                (-l <language> | --lang <language>)
                [--language-specific-primitives <language specific primitives>...]
                [--library <library>] [--model-name-prefix <model name prefix>]
                [--model-name-suffix <model name suffix>]
                [--model-package <model package>]
                [(-o <output directory> | --output <output directory>)]
                [--release-note <release note>] [--remove-operation-id-prefix]
                [--reserved-words-mappings <reserved word mappings>...]
                [(-s | --skip-overwrite)]
                [(-t <template directory> | --template-dir <template directory>)]
                [--type-mappings <type mappings>...] [(-v | --verbose)]

OPTIONS
        -a <authorization>, --auth <authorization>
            adds authorization headers when fetching the swagger definitions
            remotely. Pass in a URL-encoded string of name:header with a comma
            separating multiple values

        --additional-properties <additional properties>
            sets additional properties that can be referenced by the mustache
            templates in the format of name=value,name=value. You can also have
            multiple occurrences of this option.

        --api-package <api package>
            package for generated api classes

        --artifact-id <artifact id>
            artifactId in generated pom.xml

        --artifact-version <artifact version>
            artifact version in generated pom.xml

        -c <configuration file>, --config <configuration file>
            Path to json configuration file. File content should be in a json
            format {"optionKey":"optionValue", "optionKey1":"optionValue1"...}
            Supported options can be different for each language. Run
            config-help -l {lang} command for language specific config options.

        -D <system properties>
            sets specified system properties in the format of
            name=value,name=value (or multiple options, each with name=value)

        --git-repo-id <git repo id>
            Git repo ID, e.g. swagger-codegen.

        --git-user-id <git user id>
            Git user ID, e.g. swagger-api.

        --group-id <group id>
            groupId in generated pom.xml

        --http-user-agent <http user agent>
            HTTP user agent, e.g. codegen_csharp_api_client, default to
            'Swagger-Codegen/{packageVersion}}/{language}'

        -i <spec file>, --input-spec <spec file>
            location of the swagger spec, as URL or file (required)

        --ignore-file-override <ignore file override location>
            Specifies an override location for the .swagger-codegen-ignore file.
            Most useful on initial generation.

        --import-mappings <import mappings>
            specifies mappings between a given class and the import that should
            be used for that class in the format of type=import,type=import. You
            can also have multiple occurrences of this option.

        --instantiation-types <instantiation types>
            sets instantiation type mappings in the format of
            type=instantiatedType,type=instantiatedType.For example (in Java):
            array=ArrayList,map=HashMap. In other words array types will get
            instantiated as ArrayList in generated code. You can also have
            multiple occurrences of this option.

        --invoker-package <invoker package>
            root package for generated code

        -l <language>, --lang <language>
            client language to generate (maybe class name in classpath,
            required)

        --language-specific-primitives <language specific primitives>
            specifies additional language specific primitive types in the format
            of type1,type2,type3,type3. For example:
            String,boolean,Boolean,Double. You can also have multiple
            occurrences of this option.

        --library <library>
            library template (sub-template)

        --model-name-prefix <model name prefix>
            Prefix that will be prepended to all model names. Default is the
            empty string.

        --model-name-suffix <model name suffix>
            Suffix that will be appended to all model names. Default is the
            empty string.

        --model-package <model package>
            package for generated models

        -o <output directory>, --output <output directory>
            where to write the generated files (current dir by default)

        --release-note <release note>
            Release note, default to 'Minor update'.

        --remove-operation-id-prefix
            Remove prefix of operationId, e.g. config_getId => getId

        --reserved-words-mappings <reserved word mappings>
            specifies how a reserved name should be escaped to. Otherwise, the
            default _<name> is used. For example id=identifier. You can also
            have multiple occurrences of this option.

        -s, --skip-overwrite
            specifies if the existing files should be overwritten during the
            generation.

        -t <template directory>, --template-dir <template directory>
            folder containing the template files

        --type-mappings <type mappings>
            sets mappings between swagger spec types and generated code types in
            the format of swaggerType=generatedType,swaggerType=generatedType.
            For example: array=List,map=Map,string=String. You can also have
            multiple occurrences of this option.

        -v, --verbose
            verbose mode

 

利用Swagger Codegen根據服務生成客戶端代碼

java -jar swagger-codegen-cli-2.2.1.jar generate -i http://petstore.swagger.io/v2/swagger.json -l java -o samples/client/pestore/java

在上面這段代碼裏,使用了三個參數,分別是-i-l-oandroid

-i指定swagger描述文件的路徑,url地址或路徑文件;該參數爲必須(http://petstore.swagger.io/v2/swagger.json是官方的一個例子,咱們能夠改爲本身的服務)git

-l指定生成客戶端代碼的語言,該參數爲必須github

-o指定生成文件的位置(默認當前目錄)spring

除了能夠指定上面三個參數,還有一些經常使用的:

-c json格式的配置文件的路徑;文件爲json格式,支持的配置項因語言的不一樣而不一樣

-a 當獲取遠程swagger定義時,添加受權頭信息;URL-encoded格式化的name,逗號隔開的多個值

--api-package 指定生成的api類的包名

--artifact-id 指定pom.xmlartifactId的值

--artifact-version 指定pom.xmlartifact的版本

--group-id 指定pom.xmlgroupId的值

--model-package 指定生成的model類的包名

-s 指定該參數表示不覆蓋已經存在的文件

-t 指定模版文件所在目錄

 

生成好的客戶端代碼

生成的這些文件裏,src文件下的文件和pom.xml文件是對咱們最有用的。把它們導入到咱們習慣用的java編輯器裏,這裏以eclipse爲例,下面是導入好的客戶端的maven工程,和咱們日常新建的maven工程如出一轍(已共享到QQ羣文件:301343109)。

 

可是自動生成的客戶端代碼並不能直接使用,須要咱們作一些修改,特別是io.swagger.client.api包下的class類,咱們須要把void替換成各自的model

改好後,咱們就能夠運行客戶端test下的測試代碼,進行單元測試了。拿PetApiTest類來舉例,運行它的addPetTest()方法。

能夠看到測試成功。

 

2019.6.23 更新

咱們會發現生成的默認包是io.swagger.client.api/module,而咱們可能想要本身的包,怎麼辦呢?我看網上竟然有人說要改源碼,如下是那篇文章的內容。

這邊我想說swagger也是一個比較成熟的產品了,也這麼多人在用了,怎麼可能連修改默認的包這個基礎的需求都不提供呢,說明這篇文章的做者,根本就沒看Swagger Codegen的幫助信息,上面明明已經列出來了,只須要生成代碼的時候指定--api-package這個選項就行了。

命令我貼出來

java -jar swagger-codegen-cli-2.3.1.jar generate -i http://xxxx:8807/static/swagger.json -l java -o C:\Users\Administrator\Documents\xx-java-gen --api-package com.xxxx.client  --invoker-package com.xxxx.client.invoker --model-package com.xxxx.client.model

因此咱們在學習和工做的時候,必定要靈活,多動腦。

相關文章
相關標籤/搜索