ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Swagger Codegen 生成 Java 客户端指南:解析 google-api-client 版 AnotherFakeApi 与 testSpecialTags 调用

2026/9/24 4:51:53 拓冰建站 浏览量
Swagger Codegen 生成 Java 客户端指南:解析 google-api-client 版 AnotherFakeApi 与 testSpecialTags 调用 开发工具代码生成API设计【免费下载链接】swagger-codegenswagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.项目地址https://gitcode.com/gh_mirrors/sw/swagger-codegen点击查看免费下载本文以 swagger-codegen 仓库中的 google-api-client 版 Petstore 客户端样例为核心深入剖析自动生成的AnotherFakeApi类及其唯一接口testSpecialTags对应PATCH /another-fake/dummy。读者将掌握如何在 Java 工程中实例化并使用该 API 客户端完成一次带 JSON 请求体的 PATCH 调用同时理解这类由 OpenAPI 定义自动生成代码的底层实现原理、依赖组成与测试方式。接口速览AnotherFakeApi 提供什么能力AnotherFakeApi是 swagger-codegen 为 Petstore 测试样例生成的 API 客户端类位于 samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/api/AnotherFakeApi.java。该类仅暴露一个操作方法其文档即本指南所依据的 AnotherFakeApi.md给出的接口清单如下方法HTTP 请求描述testSpecialTagsPATCH/another-fake/dummyTo test special tags所有请求的基准地址Base Path为http://petstore.swagger.io:80/v2即文档中All URIs are relative tohttp://petstore.swagger.io:80/v2的含义。生成的实际请求路径为http://petstore.swagger.io:80/v2/another-fake/dummy。该端点的用途是验证代码生成器对特殊 tag的处理能力从底层规格定义可见这个操作被标记为 tag$another-fake?见下文规格解析包含$与?等特殊字符专门用于测试生成器在遇到非常规 tag 名时能否正确生成 API 类名与方法名。底层 OpenAPI 定义接口从何而来生成的代码并非手写而是来源于仓库中的 OpenAPI 规格文件。/another-fake/dummy的 PATCH 操作定义于 fixtures/immutable/specifications/v3/petstore3fake.yamlv2 版本见 fixtures/immutable/specifications/v2/petstorefake.yaml/another-fake/dummy: patch: tags: - $another-fake? summary: To test special tags description: To test special tags operationId: test_special_tags requestBody: description: client model content: application/json: schema: $ref: #/components/schemas/Client required: true responses: 200: description: successful operation content: application/json: schema: $ref: #/components/schemas/Client关键信息提炼operationIdtest_special_tags生成器据此经过驼峰命名转换得到方法名testSpecialTagstag$another-fake?含特殊字符正是special tags一词的由来生成器据此生成了AnotherFakeApi类请求体必填required: true类型为Client模型application/json响应200 成功返回体同样是Client模型。同一规格还被用于生成其他 Java 客户端库变体因此可以在不同 library 的样例目录中看到同名的AnotherFakeApi它们接口一致、底层 HTTP 实现各异。实战调用一段可复制的 Java 示例文档中给出了完整的调用示例直接使用生成的 API 客户端发起 PATCH 请求// Import classes: //import io.swagger.client.ApiException; //import io.swagger.client.api.AnotherFakeApi; AnotherFakeApi apiInstance new AnotherFakeApi(); Client body new Client(); // Client | client model try { Client result apiInstance.testSpecialTags(body); System.out.println(result); } catch (ApiException e) { System.err.println(Exception when calling AnotherFakeApi#testSpecialTags); e.printStackTrace(); }调用流程拆解构造客户端new AnotherFakeApi()内部默认new ApiClient()如需自定义基准地址、超时或鉴权可改用new AnotherFakeApi(ApiClient apiClient)构造器或用setApiClient(...)替换构造请求体new Client()并设置属性见下文模型一节发起调用apiInstance.testSpecialTags(body)返回Client类型结果异常处理注意testSpecialTags声明抛出java.io.IOException而非ApiException这是 google-api-client 库实现的显著特点详见源码解析一节。参数说明名称类型描述备注bodyClientclient model必填规格中required: true传null会触发IllegalArgumentException返回值与响应细节Return typeClientAuthorization无需鉴权No authorization requiredContent-Typeapplication/jsonAcceptapplication/json源码级实现google-api-client 版 testSpecialTags 是如何工作的生成的实现位于 AnotherFakeApi.java其核心是testSpecialTagsForHttpResponse(Client body)方法完整呈现了基于 Google HTTP Clientgoogle-api-client的请求构建链路public HttpResponse testSpecialTagsForHttpResponse(Client body) throws IOException { // verify the required parameter body is set if (body null) { throw new IllegalArgumentException(Missing the required parameter body when calling testSpecialTags); } UriBuilder uriBuilder UriBuilder.fromUri(apiClient.getBasePath() /another-fake/dummy); String url uriBuilder.build().toString(); GenericUrl genericUrl new GenericUrl(url); HttpContent content apiClient.new JacksonJsonHttpContent(body); return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PATCH, genericUrl, content).execute(); }实现要点URL 构建使用javax.ws.rs.core.UriBuilder来自 Jersey Common拼接apiClient.getBasePath() /another-fake/dummy再转为 Google HTTP Client 的GenericUrl。在规格模板 pom 中可以看到jersey-common正是为此引入的依赖请求体序列化通过apiClient.new JacksonJsonHttpContent(body)将Client模型序列化为 JSON同时提供接受java.io.InputStream的重载版本可自定义媒体类型默认Json.MEDIA_TYPEHTTP 动词HttpMethods.PATCH明确指定 PATCH 方法查询参数扩展另有testSpecialTags(Client body, MapString, Object params)重载可附加查询参数——Collection会被展开为多个同名参数Object[]逐项追加其余值直接queryParam追加响应解析testSpecialTags通过apiClient.getObjectMapper().readValue(response.getContent(), new TypeReferenceClient(){})将响应体反序列化为Client对象。类本身还提供了标准的getApiClient()/setApiClient()访问器便于在运行时切换或注入ApiClient实例。数据模型Client请求体与返回值对应的模型类为 samples/client/petstore/java/google-api-client/src/main/java/io/swagger/client/model/Client.java是自动生成的 POJOpublic class Client { JsonProperty(client) private String client null; public Client client(String client) { this.client client; return this; } public String getClient() { return client; } public void setClient(String client) { this.client client; } // equals / hashCode / toString 均由生成器产出 }模型只有一个字符串字段clientJSON 属性名与字段同名并提供链式 setterclient(...)返回this、标准 getter/setter以及基于Objects的equals/hashCode与格式化toString。实际使用时可按需设置Client body new Client().client(example-client);测试用例如何验证生成的 API仓库为每个生成的 API 类配套了 JUnit 测试骨架见 samples/client/petstore/java/google-api-client/src/test/java/io/swagger/client/api/AnotherFakeApiTest.javaIgnore public class AnotherFakeApiTest { private final AnotherFakeApi api new AnotherFakeApi(); Test public void testSpecialTagsTest() throws IOException { Client body null; Client response api.testSpecialTags(body); // TODO: test validations } }要点测试类标注了Ignore属于生成器产出的占位骨架默认不参与 CI 执行需接入真实服务后再启用验证了testSpecialTags抛出的异常类型为java.io.IOExceptiongoogle-api-client 风格的异常模型api字段直接以无参构造器创建说明无需额外配置即可完成客户端实例化。工程背景google-api-client 库的依赖组成该样例是 swagger-codegen Java 客户端多种 HTTP library 变体之一。生成它所用的模板与依赖配置位于 modules/swagger-codegen/src/main/resources/Java/libraries/google-api-client/其中 pom.mustache 明确了核心依赖google-api-clientcom.google.api-client:google-api-client版本 1.23.0HTTP 传输与请求执行的基础jersey-commonorg.glassfish.jersey.core:jersey-common提供javax.ws.rs.core.UriBuilder用于 URL 模板构建jackson-core / jackson-annotations / jackson-databindJSON 序列化与反序列化JacksonJsonHttpContent、ObjectMapperswagger-annotationsio.swagger:swagger-annotations模型与接口上的 Swagger 注解junittest scope测试骨架依赖。生成器通过JavaClientCodegen的librarygoogle-api-client配置切换该模板族用户可在生成命令中指定--library google-api-client获得同样基于 Google HTTP Client 的 Java 客户端。小结与延伸AnotherFakeApi.testSpecialTags虽只是 Petstore 测试规格中的一个端点却是理解 swagger-codegen 生成客户端完整链路的绝佳样本从 OpenAPI 规格 中的operationId与特殊 tag到自动生成的 API 类 与 模型类再到配套的 JUnit 测试 与 模板 pom每一环都可独立查阅与验证。读者可将同样方法应用于仓库内其他生成样例如FakeApi、PetApi等 java/google-api-client 目录 下文档快速掌握自己所生成客户端的调用与定制方式。赞分享开发工具代码生成API设计【免费下载链接】swagger-codegenswagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.项目地址https://gitcode.com/gh_mirrors/sw/swagger-codegen点击查看免费下载相关推荐Swagger-Codegen JavaJersey 1客户端详解AnotherFakeApi 与 testSpecialTags 的生成与调用Swagger Codegen JavaJersey 1客户端详解AnotherFakeApi 与 testSpecialTags 的生成与调用 导读 A开发工具代码生成API设计swagger-codegen 生成的 C 客户端 API 类详解以 AnotherFakeApi 与 TestSpecialTags 为例swagger codegen 生成的 C 客户端 API 类详解以 AnotherFakeApi 与 TestSpecialTags 为例 本指南围绕 sw开发工具代码生成API设计swagger-codegen 生成的 Jersey2 客户端 API 文档解析以 AnotherFakeApi 的 testSpecialTags 为例swagger codegen 生成的 Jersey2 客户端 API 文档解析以 AnotherFakeApi 的 testSpecialTags 为例 本开发工具代码生成API设计创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考