java 生成客户端代码_swagger-codegen自动生成代码工具的介绍与使用

一、Swagger Codegen简介

Swagger Codegen是一个开源的代码生成器,根据Swagger定义的RESTful API可以自动建立服务端和客户端的连接。Swagger Codegen的源码可以在Github上找到。

二、Swagger Codegen安装

首先机器上需要安装jdk,具体Java, version 7 or higher,然后在这里(https://oss.sonatype.org/content/repositories/releases/io/swagger/)找到需要的Swagger Codegen版本来安装,不过官方是推荐最新版本。

只要下载一个cli的jar文件就可以了,例如, swagger-codegen-cli-2.2.1.jar(已共享到QQ群文件:301343109)。也可以直接在命令行里下载,例如

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

下载好了,运行

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]

三、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 | --auth )]

[--additional-properties ...]

[--api-package ] [--artifact-id ]

[--artifact-version ]

[(-c | --config )]

[-D ...] [--git-repo-id ]

[--git-user-id ] [--group-id ]

[--http-user-agent ]

(-i | --input-spec )

[--ignore-file-override ]

[--import-mappings ...]

[--instantiation-types ...]

[--invoker-package ]

(-l | --lang )

[--language-specific-primitives ...]

[--library ] [--model-name-prefix ]

[--model-name-suffix ]

[--model-package ]

[(-o | --output )]

[--release-note ] [--remove-operation-id-prefix]

[--reserved-words-mappings ...]

[(-s | --skip-overwrite)]

[(-t | --template-dir )]

[--type-mappings ...] [(-v | --verbose)]

OPTIONS-a , --auth adds authorization headers when fetching the swagger definitions

remotely. Passin a URL-encoded stringof name:header with a comma

separating multiple values--additional-properties sets additional properties that can be referenced by the mustache

templatesin the format of name=value,name=value. You can also have

multiple occurrences ofthisoption.--api-package packageforgenerated api classes--artifact-id artifactIdingenerated pom.xml--artifact-version artifact versioningenerated pom.xml-c , --config Path to json configuration file. File content should beina json

format {"optionKey":"optionValue", "optionKey1":"optionValue1"...}

Supported options can be differentforeach language. Run

config-help -l {lang} command forlanguage specific config options.-D sets specified system propertiesinthe format of

name=value,name=value (or multiple options, each with name=value)--git-repo-id Git repo ID, e.g. swagger-codegen.--git-user-id Git user ID, e.g. swagger-api.--group-id groupIdingenerated pom.xml--http-user-agent HTTP user agent, e.g. codegen_csharp_api_client,defaultto'Swagger-Codegen/{packageVersion}}/{language}'

-i , --input-spec location of the swagger spec,asURL or file (required)--ignore-file-override Specifies anoverride location for the .swagger-codegen-ignore file.

Most useful on initial generation.--import-mappings specifies mappings between a givenclassand the import that should

be usedfor that class in the format of type=import,type=import. You

can also have multiple occurrences ofthisoption.--instantiation-types sets instantiation type mappingsinthe format of

type=instantiatedType,type=instantiatedType.For example (inJava):

array=ArrayList,map=HashMap. In other words array types will getinstantiatedas ArrayList ingenerated code. You can also have

multiple occurrences ofthisoption.--invoker-package root packageforgenerated code-l , --lang client language to generate (maybeclass name inclasspath,

required)--language-specific-primitives specifies additional language specific primitive typesinthe format

of type1,type2,type3,type3. For example:

String,boolean,Boolean,Double. You can also have multiple

occurrences ofthisoption.--library library template (sub-template)--model-name-prefix Prefix that will be prepended to all model names. Defaultisthe

emptystring.--model-name-suffix Suffix that will be appended to all model names. Defaultisthe

emptystring.--model-package packageforgenerated models-o , --output

where to write the generated files (current dir by default)--release-note Release note,default to 'Minor update'.--remove-operation-id-prefix

Remove prefix of operationId, e.g. config_getId=>getId--reserved-words-mappings specifies how a reserved name should be escaped to. Otherwise, thedefault _ is used. For example id=identifier. You can also

have multiple occurrences ofthisoption.-s, --skip-overwrite

specifiesifthe existing files should be overwritten during the

generation.-t , --template-dir folder containing the template files--type-mappings sets mappings between swagger spec types and generated code typesinthe format of swaggerType=generatedType,swaggerType=generatedType.

For example: array=List,map=Map,string=String. You can also have

multiple occurrences ofthisoption.-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和-o。

-i指定swagger描述文件的路径,url地址或路径文件;该参数为必须(http://petstore.swagger.io/v2/swagger.json是官方的一个例子,我们可以改成自己的服务)

-l指定生成客户端代码的语言,该参数为必须

-o指定生成文件的位置(默认当前目录)

除了可以指定上面三个参数,还有一些常用的:

-c json格式的配置文件的路径;文件为json格式,支持的配置项因语言的不同而不同

-a 当获取远程swagger定义时,添加授权头信息;URL-encoded格式化的name,逗号隔开的多个值

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

--artifact-id 指定pom.xml的artifactId的值

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

--group-id 指定pom.xml的groupId的值

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

-s 指定该参数表示不覆盖已经存在的文件

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

生成好的客户端代码

44558d0f368a088a5f13d7d970f57fb6.png

生成的这些文件里,src文件下的文件和pom.xml文件是对我们最有用的。把它们导入到我们习惯用的java编辑器里,这里以eclipse为例,下面是导入好的客户端的maven工程,和我们平常新建的maven工程一模一样(已共享到QQ群文件:301343109)。

87150469b4ad2c6d5cebcdc9e00cb38f.png

但是自动生成的客户端代码并不能直接使用,需要我们做一些修改,特别是io.swagger.client.api包下的class类,我们需要把void替换成各自的model。

改好后,我们就可以运行客户端test下的测试代码,进行单元测试了。拿PetApiTest类来举例,运行它的addPetTest()方法。

80fdb9fb7e70714da3a43555bcb29b7b.png

可以看到测试成功。

2019.6.23 更新

我们会发现生成的默认包是io.swagger.client.api/module,而我们可能想要自己的包,怎么办呢?我看网上居然有人说要改源码,以下是那篇文章的内容。

bd0e1d78cf98c8fcd656cd9224c6e5eb.png

这边我想说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

所以我们在学习和工作的时候,一定要灵活,多动脑。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值