ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Swagger Codegen 生成 Java Jersey 1 客户端:PetApi 八个 Petstore 接口完整实战指南

Swagger Codegen 生成 Java Jersey 1 客户端:PetApi 八个 Petstore 接口完整实战指南 开发工具代码生成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 仓库中 PetApi.md 文档展开。这是一份由 swagger-codegen 模板驱动引擎自动生成的 Jersey 1 版 Java API 客户端接口文档完整覆盖 Swagger Petstore 中PetApi的 8 个 REST 接口增、删、改、查、表单更新、文件上传。读完本文你将掌握生成客户端的接入方式、两种认证方案OAuth2 与 API Key的配置方法、每个接口的签名与调用示例并深入理解自动生成代码的底层实现模式与测试验证方式可直接用于驱动真实 Petstore 服务的开发调试。一、文档来源与适用场景PetApi.md位于 samples/client/petstore/java/jersey1/docs/ 目录它是 swagger-codegen 对 Petstore 示例规范执行生成后产出的 API 文档。该项目本身是一个模板驱动的代码生成引擎解析 OpenAPI / Swagger 定义后可生成多种语言的 API 客户端、服务端桩代码与文档。本文涉及的样例即java生成器HTTP 库为 Jersey 1.x的产物同一套规范还生成了 PetApi.java 客户端类、Pet.java 数据模型以及配套的 PetApiTest.java 单元测试。按文档约定所有 URI 均相对于http://petstore.swagger.io:80/v2这个基路径在生成的 ApiClient.java 中作为默认值也可在运行时通过setBasePath覆盖参见测试 PetApiTest.java。PetApi覆盖的 8 个接口一览方法HTTP 请求描述addPetPOST/petAdd a new pet to the storedeletePetDELETE/pet/{petId}Deletes a petfindPetsByStatusGET/pet/findByStatusFinds Pets by statusfindPetsByTagsGET/pet/findByTagsFinds Pets by tagsgetPetByIdGET/pet/{petId}Find pet by IDupdatePetPUT/petUpdate an existing petupdatePetWithFormPOST/pet/{petId}Updates a pet in the store with form datauploadFilePOST/pet/{petId}/uploadImageuploads an image二、客户端安装与依赖引入在调用接口之前需要先把生成的客户端库引入项目。参照 README.md 的说明构建该库要求本机安装 Mavenmvn install如需部署到远程 Maven 仓库可先配置仓库 settings 后执行mvn deployMaven 用户在项目 POM 中加入依赖dependency groupIdio.swagger/groupId artifactIdswagger-java-client/artifactId version1.0.0/version scopecompile/scope /dependencyGradle 用户在构建文件中加入compile io.swagger:swagger-java-client:1.0.0其他方式先执行mvn package打包再手动安装生成的 JARtarget/swagger-java-client-1.0.0.jartarget/lib/*.jar三、认证方案配置Petstore 定义了两种认证方案详见 README.md 的 Documentation for Authorization 一节它们由 swagger-codegen 根据规范中的securityDefinitions自动映射到客户端库的auth包3.1 petstore_authOAuth2implicit 流类型OAuthFlowimplicitAuthorization URLhttp://petstore.swagger.io/api/oauth/dialogScopeswrite:petsmodify pets in your accountread:petsread your pets在代码中通过默认ApiClient获取认证实例并设置令牌ApiClient defaultClient Configuration.getDefaultApiClient(); OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN);3.2 api_keyAPI Key类型API key参数名api_key位置HTTP 请求头ApiClient defaultClient Configuration.getDefaultApiClient(); ApiKeyAuth api_key (ApiKeyAuth) defaultClient.getAuthentication(api_key); api_key.setApiKey(YOUR API KEY); // 如需设置前缀例如 Token默认为 null //api_key.setApiKeyPrefix(Token);这两种认证与接口的对应关系在源码中清晰可见PetApi.java中addPet、deletePet、findPetsByStatus、findPetsByTags、updatePet、updatePetWithForm、uploadFile七个方法都声明了localVarAuthNames new String[] { petstore_auth }而getPetById声明的是new String[] { api_key }见 PetApi.java 与 PetApi.java。四、addPet新增宠物void addPet(Pet body)——POST /pet调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); Pet body new Pet(); // Pet | Pet object that needs to be added to the store try { apiInstance.addPet(body); } catch (ApiException e) { System.err.println(Exception when calling PetApi#addPet); e.printStackTrace(); }参数NameTypeDescriptionNotesbodyPetPet object that needs to be added to the store返回类型与请求头Return typenull空响应体Authorizationpetstore_authContent-Typeapplication/json,application/xmlAcceptapplication/xml,application/json源码实现要点在 PetApi.java 中addPet首先校验必填参数body若为null则抛出ApiException(400, Missing the required parameter body when calling addPet)随后将请求体对象直接赋给localVarPostBody设置Accept与Content-Type头后调用apiClient.invokeAPI(...)发送POST。请求体的序列化与反序列化由ApiClient基于 Jackson 完成。五、deletePet删除宠物void deletePet(Long petId, String apiKey)——DELETE /pet/{petId}调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); Long petId 789L; // Long | Pet id to delete String apiKey apiKey_example; // String | try { apiInstance.deletePet(petId, apiKey); } catch (ApiException e) { System.err.println(Exception when calling PetApi#deletePet); e.printStackTrace(); }参数NameTypeDescriptionNotespetIdLongPet id to deleteapiKeyString[optional]返回类型与请求头Return typenull空响应体Authorizationpetstore_authContent-Type未定义Acceptapplication/xml,application/json源码实现要点PetApi.java 展示了路径参数的处理方式路径模板/pet/{petId}通过replaceAll(\\{petId\\}, apiClient.escapeString(petId.toString()))完成 URL 编码替换。可选的apiKey参数在非空时被放入localVarHeaderParams键名为api_key——注意这与认证方案api_key同名同位置属于规范中接口级 header 参数与全局认证的典型结合。六、findPetsByStatus按状态查询ListPet findPetsByStatus(ListString status)——GET /pet/findByStatus描述可传入多个状态值使用逗号分隔的字符串。合法的枚举值为available、pending、sold。调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); ListString status Arrays.asList(status_example); // ListString | Status values that need to be considered for filter try { ListPet result apiInstance.findPetsByStatus(status); System.out.println(result); } catch (ApiException e) { System.err.println(Exception when calling PetApi#findPetsByStatus); e.printStackTrace(); }参数NameTypeDescriptionNotesstatusListStringStatus values that need to be considered for filter[enum: available, pending, sold]返回类型与请求头Return typeListPetAuthorizationpetstore_authContent-Type未定义Acceptapplication/xml,application/json源码实现要点这是第一个返回集合的方法。PetApi.java 中status列表通过apiClient.parameterToPairs(csv, status, status)序列化为逗号分隔的查询参数localVarCollectionQueryParams返回类型使用 Jersey 1 的GenericTypeListPet包装invokeAPI的最后一个参数即为返回类型的类型标记。文档中标注的枚举值available / pending / sold与数据模型 Pet.java 中定义的StatusEnumAVAILABLE(available)、PENDING(pending)、SOLD(sold)完全一致该枚举同时标注了 Jackson 的JsonValue/JsonCreator以支持 JSON 双向序列化。七、findPetsByTags按标签查询ListPet findPetsByTags(ListString tags)——GET /pet/findByTags描述可传入多个标签使用逗号分隔的字符串。测试时可用tag1, tag2, tag3。调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); ListString tags Arrays.asList(tags_example); // ListString | Tags to filter by try { ListPet result apiInstance.findPetsByTags(tags); System.out.println(result); } catch (ApiException e) { System.err.println(Exception when calling PetApi#findPetsByTags); e.printStackTrace(); }参数NameTypeDescriptionNotestagsListStringTags to filter by返回类型与请求头Return typeListPetAuthorizationpetstore_authContent-Type未定义Acceptapplication/xml,application/json源码实现要点与findPetsByStatus结构一致tags同样经parameterToPairs(csv, tags, tags)序列化为查询参数。值得注意的是生成代码中该方法带有Deprecated注解见 PetApi.java这是 swagger-codegen 对规范中deprecated: true标记的忠实映射——规范层面已声明该接口废弃生成器会同步在客户端标注。八、getPetById按 ID 查询Pet getPetById(Long petId)——GET /pet/{petId}描述根据 ID 返回单个宠物。调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure API key authorization: api_key ApiKeyAuth api_key (ApiKeyAuth) defaultClient.getAuthentication(api_key); api_key.setApiKey(YOUR API KEY); // Uncomment the following line to set a prefix for the API key, e.g. Token (defaults to null) //api_key.setApiKeyPrefix(Token); PetApi apiInstance new PetApi(); Long petId 789L; // Long | ID of pet to return try { Pet result apiInstance.getPetById(petId); System.out.println(result); } catch (ApiException e) { System.err.println(Exception when calling PetApi#getPetById); e.printStackTrace(); }参数NameTypeDescriptionNotespetIdLongID of pet to return返回类型与请求头Return typePetAuthorizationapi_keyContent-Type未定义Acceptapplication/xml,application/json源码实现要点这是 PetApi 中唯一使用api_key认证的方法PetApi.java。路径参数petId同样经escapeString编码替换返回类型为GenericTypePet。测试 PetApiTest.java 中测试基架正是通过(ApiKeyAuth) api.getApiClient().getAuthentication(api_key)并setApiKey(special-key)完成鉴权配置。九、updatePet整体更新宠物void updatePet(Pet body)——PUT /pet调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); Pet body new Pet(); // Pet | Pet object that needs to be added to the store try { apiInstance.updatePet(body); } catch (ApiException e) { System.err.println(Exception when calling PetApi#updatePet); e.printStackTrace(); }参数NameTypeDescriptionNotesbodyPetPet object that needs to be added to the store返回类型与请求头Return typenull空响应体Authorizationpetstore_authContent-Typeapplication/json,application/xmlAcceptapplication/xml,application/json源码实现要点PetApi.java 中updatePet与addPet的唯一本质区别是 HTTP 方法从POST换为PUT请求路径同为/pet其余参数校验与请求头设置逻辑完全一致。PUT 的语义为整体替换调用前应构造一个完整的Pet对象含 id、name、category、photoUrls、tags、status。十、updatePetWithForm表单更新宠物void updatePetWithForm(Long petId, String name, String status)——POST /pet/{petId}调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); Long petId 789L; // Long | ID of pet that needs to be updated String name name_example; // String | Updated name of the pet String status status_example; // String | Updated status of the pet try { apiInstance.updatePetWithForm(petId, name, status); } catch (ApiException e) { System.err.println(Exception when calling PetApi#updatePetWithForm); e.printStackTrace(); }参数NameTypeDescriptionNotespetIdLongID of pet that needs to be updatednameStringUpdated name of the pet[optional]statusStringUpdated status of the pet[optional]返回类型与请求头Return typenull空响应体Authorizationpetstore_authContent-Typeapplication/x-www-form-urlencodedAcceptapplication/xml,application/json源码实现要点与上述基于 JSON 请求体的接口不同该方法演示了表单参数的生成模式PetApi.java可选的name与status在非空时被写入localVarFormParamslocalVarFormParams.put(name, name)Content-Type声明为application/x-www-form-urlencoded。测试 PetApiTest.java 验证了此行为先addPet创建宠物再以updatePetWithForm(fetched.getId(), furt, null)更新名称随后getPetById断言名称已变为furt。十一、uploadFile上传图片ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file)——POST /pet/{petId}/uploadImage调用示例// Import classes: //import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; //import io.swagger.client.Configuration; //import io.swagger.client.auth.*; //import io.swagger.client.api.PetApi; ApiClient defaultClient Configuration.getDefaultApiClient(); // Configure OAuth2 access token for authorization: petstore_auth OAuth petstore_auth (OAuth) defaultClient.getAuthentication(petstore_auth); petstore_auth.setAccessToken(YOUR ACCESS TOKEN); PetApi apiInstance new PetApi(); Long petId 789L; // Long | ID of pet to update String additionalMetadata additionalMetadata_example; // String | Additional data to pass to server File file new File(/path/to/file.txt); // File | file to upload try { ModelApiResponse result apiInstance.uploadFile(petId, additionalMetadata, file); System.out.println(result); } catch (ApiException e) { System.err.println(Exception when calling PetApi#uploadFile); e.printStackTrace(); }参数NameTypeDescriptionNotespetIdLongID of pet to updateadditionalMetadataStringAdditional data to pass to server[optional]fileFilefile to upload[optional]返回类型与请求头Return typeModelApiResponseAuthorizationpetstore_authContent-Typemultipart/form-dataAcceptapplication/json源码实现要点这是唯一的多部分上传接口PetApi.java可选的additionalMetadata与file被写入表单参数Content-Type为multipart/form-dataAccept仅声明application/json返回类型为GenericTypeModelApiResponse。测试 PetApiTest.java 展示了完整用法先创建并写入一个本地hello.txt文件再调用api.uploadFile(pet.getId(), a test file, new File(file.getAbsolutePath()))上传。十二、生成代码的统一实现模式与测试验证纵览整个 PetApi.java共 408 行swagger-codegen 生成的每个接口方法都遵循高度一致的模板模式可作为阅读其他生成客户端StoreApi、UserApi、FakeApi 等的通用参考必填参数校验任何标记为 required 的参数若为null立即抛出ApiException(400, Missing the required parameter xxx when calling yyy)。路径模板替换{petId}这类路径参数统一通过apiClient.escapeString(...)做 URL 编码后replaceAll进路径模板。参数分类装载按参数类型分别装入localVarQueryParams普通查询参数、localVarCollectionQueryParams集合查询参数如csv逗号分隔、localVarHeaderParamsheader 参数、localVarFormParams表单参数与localVarPostBodyJSON 请求体。内容协商apiClient.selectHeaderAccept(...)与apiClient.selectHeaderContentType(...)根据方法声明的 Accept / Content-Type 数组选择最优值。认证声明localVarAuthNames数组列出本方法所需的认证方案名ApiClient.invokeAPI内部据此注入对应的 OAuth 令牌或 API Key。返回类型泛型化无返回值的方法传null有返回值的方法用GenericTypeT显式声明反序列化目标类型。上述模式在 PetApiTest.java 中得到了端到端验证testCreateAndGetPet验证创建后可回读且字段一致testFindPetsByStatus与testFindPetsByTags验证过滤查询能命中刚更新的宠物testDeletePet验证删除后再次查询抛出ApiException且e.getCode() 404testUpdatePet与testUpdatePetWithForm验证两种更新路径。这些测试同时确认了默认基路径为http://petstore.swagger.io:80/v2并可通过构造器或 setter 替换ApiClient实例以覆盖基路径与调试开关setDebugging(true)。十三、实战提示线程安全官方 README 建议在多线程环境下为每个线程创建独立的ApiClient实例new PetApi(new ApiClient())避免共享客户端潜在的并发问题。基路径覆盖接入自建服务时通过api.getApiClient().setBasePath(http://your-host:port/v2)即可切换无需重新生成代码。调试开关setDebugging(true)可输出完整的请求 / 响应日志便于定位序列化或鉴权问题。数据模型配套接口参数与返回值对应的 Pet.md、ModelApiResponse.md 等模型文档同样由生成器产出字段名、类型与 JSON 序列化规则如StatusEnum的JsonValue/JsonCreator可在其中核对。文档与代码同源本文档与客户端代码由同一规范经 swagger-codegen 模板驱动生成若规范变更只需重新运行生成器即可同步刷新接口文档与实现这正是 swagger-codegen 以文档、客户端、桩代码三者为统一产物的核心工作流。赞分享开发工具代码生成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 生成 Dart 浏览器客户端 PetApi 完整指南Petstore 宠物接口调用实战swagger codegen 生成 Dart 浏览器客户端 PetApi 完整指南Petstore 宠物接口调用实战 本指南以 swagger codege开发工具代码生成API设计debugging-toolkit 插件智能调试实战用 /smart-debug 完成从问题分诊到根因修复的全流程debugging toolkit 插件智能调试实战用 /smart debug 完成从问题分诊到根因修复的全流程 本文以 agents24/agents 仓开发工具代码生成API设计Swagger Codegen 生成的 Jersey 1 Java 客户端 FakeApi 完全使用指南Swagger Codegen 生成的 Jersey 1 Java 客户端 FakeApi 完全使用指南 本篇指南以 swagger codegen 生成的 J开发工具代码生成API设计创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表