ARTICLE DETAIL

资讯详情

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

swagger-codegen 生成 Dart 浏览器客户端 PetApi 完整指南:Petstore 宠物接口调用实战

swagger-codegen 生成 Dart 浏览器客户端 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 生成器为 Dart 浏览器客户端swagger-browser-client产出的 API 参考文档为主线系统讲解PetApi全部 8 个接口的方法签名、请求路径、参数、返回类型、鉴权方式与 HTTP 头并结合 lib/api/pet_api.dart、lib/api_client.dart 等生成源码剖析底层调用链。读完本文你将掌握在 Dart/Flutter Web 环境中完整调用 Petstore 宠物管理 API增删改查、按状态/标签检索、表单更新、图片上传的实战能力。该示例客户端由 Swagger Codegen 依据 OpenAPI/Swagger 定义自动生成API 版本 1.0.0构建包为io.swagger.codegen.languages.DartClientCodegen所有接口基础路径相对http://petstore.swagger.io/v2详见该包根目录的 README.md。环境要求与包引入运行环境根据该生成包的 README.md 说明Dart 1.20.0 或更高版本或者Flutter 0.0.20 或更高版本由于这是一个browser 专用客户端底层使用package:http的BrowserClient见 lib/api_client.dart因此运行环境面向浏览器而非纯 Dart VM 服务端。依赖声明pubspec.yaml在项目pubspec.yaml中声明依赖即可安装。若包已发布到 Git 仓库写法如下name: swagger version: 1.0.0 description: Swagger API client dependencies: swagger: git: https://github.com/GIT_USER_ID/GIT_REPO_ID.git version: any若使用本地路径可改为dependencies: swagger: path: /path/to/swagger生成包自身的 pubspec.yaml 仅依赖http: 0.11.1 0.12.0这是浏览器 HTTP 请求的基础。引入 API 包所有 API 类、模型与基础设施都封装在单一 libraryswagger.api中使用时只需一条 importimport package:swagger/api.dart;lib/api.dart 通过part指令把api_client.dart、api_helper.dart、api_exception.dart、三个 auth 实现authentication.dart、api_key_auth.dart、oauth.dart、http_basic_auth.dart、三个 API 类pet_api.dart、store_api.dart、user_api.dart以及全部模型文件组合进同一个库并声明了全局默认客户端defaultApiClient new ApiClient()。PetApi 接口总览PetApi位于 lib/api/pet_api.dart覆盖 Petstore 宠物资源的完整操作。全部方法均基于默认客户端实例化var api_instance new PetApi();PetApi的构造方法接受一个可选的ApiClientPetApi([ApiClient apiClient]) : apiClient apiClient ?? defaultApiClient;。若需要自定义basePath或鉴权配置可传入自建ApiClient实例。下表为该类提供的 8 个接口方法汇总与文档 PetApi.md 一致方法HTTP 请求描述addPetPOST/pet向商店添加新宠物deletePetDELETE/pet/{petId}删除宠物findPetsByStatusGET/pet/findByStatus按状态查找宠物findPetsByTagsGET/pet/findByTags按标签查找宠物getPetByIdGET/pet/{petId}按 ID 查找宠物updatePetPUT/pet更新已有宠物updatePetWithFormPOST/pet/{petId}以表单数据更新宠物uploadFilePOST/pet/{petId}/uploadImage上传图片addPet — 添加新宠物addPet(body)向商店添加一只新宠物。请求体为完整Pet对象。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var body new Pet(); // Pet | Pet object that needs to be added to the store try { api_instance.addPet(body); } catch (e) { print(Exception when calling PetApi-addPet: $e\n); }参数名称类型描述备注bodyPet需要添加到商店的 Pet 对象必填返回类型void空响应体。鉴权petstore_authOAuth2implicit 流授权 URLhttp://petstore.swagger.io/api/oauth/dialogScope 包括write:pets与read:pets。HTTP 请求头Content-Type:application/json,application/xmlAccept:application/xml,application/json源码对应实现在 lib/api/pet_api.dart 中addPet首先校验必填参数body为空时抛出ApiException(400, Missing required param: body)随后构造路径/pet声明contentTypes [application/json,application/xml]取首个类型作为请求Content-Type并将authNames设为[petstore_auth]最后通过apiClient.invokeAPI(path, POST, queryParams, postBody, headerParams, formParams, contentType, authNames)发起请求。响应statusCode 400时抛出异常否则返回空值。deletePet — 删除宠物deletePet(petId, apiKey)根据宠物 ID 删除宠物。注意该接口在 OpenAPI 定义中额外声明了一个可选的apiKey请求头参数header 名api_key因此签名中apiKey作为可选命名参数出现。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var petId 789; // int | Pet id to delete var apiKey apiKey_example; // String | try { api_instance.deletePet(petId, apiKey); } catch (e) { print(Exception when calling PetApi-deletePet: $e\n); }参数名称类型描述备注petIdint要删除的宠物 ID必填apiKeyStringheader 参数可选返回类型void空响应体。鉴权petstore_auth。HTTP 请求头Content-Type: 未定义Accept:application/xml,application/json源码对应实现lib/api/pet_api.dart 中deletePet通过/pet/{petId}.replaceAll({format},json).replaceAll({ petId }, petId.toString())完成路径参数插值并将headerParams[api_key] apiKey写入请求头最终以DELETE方法调用invokeAPI。findPetsByStatus — 按状态查找宠物ListPet findPetsByStatus(status)根据状态筛选宠物。多个状态值可以用逗号分隔的字符串提供例如available,pending这正是生成代码中 collectionFormat 为csv的典型场景。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var status []; // ListString | Status values that need to be considered for filter try { var result api_instance.findPetsByStatus(status); print(result); } catch (e) { print(Exception when calling PetApi-findPetsByStatus: $e\n); }参数名称类型描述备注statusListString需要参与筛选的状态值必填返回类型ListPet鉴权petstore_auth。HTTP 请求头Content-Type: 未定义Accept:application/xml,application/json源码对应实现lib/api/pet_api.dart 中查询参数通过queryParams.addAll(_convertParametersForCollectionFormat(csv, status, status))生成。_convertParametersForCollectionFormat定义在 lib/api_helper.dart当集合格式为multi时每个元素生成独立查询参数否则按csv,、ssv空格、tsv\t、pipes|四种分隔符之一拼接成一个参数值默认csv。响应反序列化使用apiClient.deserialize(response.body, ListPet)后逐项映射为Pet对象列表。findPetsByTags — 按标签查找宠物ListPet findPetsByTags(tags)按标签筛选宠物。多个标签以逗号分隔字符串提供文档建议可用tag1, tag2, tag3进行测试。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var tags []; // ListString | Tags to filter by try { var result api_instance.findPetsByTags(tags); print(result); } catch (e) { print(Exception when calling PetApi-findPetsByTags: $e\n); }参数名称类型描述备注tagsListString用于过滤的标签必填返回类型ListPet鉴权petstore_auth。HTTP 请求头Content-Type: 未定义Accept:application/xml,application/json源码对应实现实现与findPetsByStatus完全同构lib/api/pet_api.dart只是路径变为/pet/findByTags、集合格式同样为csv、鉴权同为petstore_auth。getPetById — 按 ID 查找宠物Pet getPetById(petId)根据宠物 ID 返回单只宠物。这是唯一一个使用api_key 头部鉴权的接口也是文档示例中展示 API Key 前缀配置如Bearer的范例。示例import package:swagger/api.dart; // TODO Configure API key authorization: api_key //swagger.api.Configuration.apiKey{api_key} YOUR_API_KEY; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //swagger.api.Configuration.apiKeyPrefix{api_key} Bearer; var api_instance new PetApi(); var petId 789; // int | ID of pet to return try { var result api_instance.getPetById(petId); print(result); } catch (e) { print(Exception when calling PetApi-getPetById: $e\n); }参数名称类型描述备注petIdint要返回的宠物 ID必填返回类型Pet鉴权api_keyAPI Key参数名api_key位于 HTTP 请求头。HTTP 请求头Content-Type: 未定义Accept:application/xml,application/json源码对应实现lib/api/pet_api.dart 中该接口的authNames [api_key]与其余接口的[petstore_auth]不同。响应通过apiClient.deserialize(response.body, Pet) as Pet反序列化为单个Pet对象。API Key 鉴权底层机制API Key 由 lib/auth/api_key_auth.dart 中的ApiKeyAuth类实现构造时传入locationheader或query与paramName此处为api_key。applyToParams中若设置了apiKeyPrefix实际发送值为$apiKeyPrefix $apiKey例如Bearer key否则直接发送apiKeylocation header时写入headerParams[paramName]location query时追加到queryParams。updatePet — 更新已有宠物updatePet(body)更新商店中已存在的宠物。语义上要求传入完整对象覆盖式更新请求体为Pet。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var body new Pet(); // Pet | Pet object that needs to be added to the store try { api_instance.updatePet(body); } catch (e) { print(Exception when calling PetApi-updatePet: $e\n); }参数名称类型描述备注bodyPet需要更新到商店的 Pet 对象必填返回类型void空响应体。鉴权petstore_auth。HTTP 请求头Content-Type:application/json,application/xmlAccept:application/xml,application/json源码对应实现lib/api/pet_api.dart 中与addPet几乎一致区别仅在于 HTTP 方法为PUT。这符合 REST 语义POST /pet创建、PUT /pet全量更新同一资源。updatePetWithForm — 以表单数据更新宠物updatePetWithForm(petId, name, status)以application/x-www-form-urlencoded表单方式更新宠物的名称与状态而不是 JSON 请求体。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var petId 789; // int | ID of pet that needs to be updated var name name_example; // String | Updated name of the pet var status status_example; // String | Updated status of the pet try { api_instance.updatePetWithForm(petId, name, status); } catch (e) { print(Exception when calling PetApi-updatePetWithForm: $e\n); }参数名称类型描述备注petIdint需要更新的宠物 ID必填nameString更新后的宠物名称可选statusString更新后的宠物状态可选返回类型void空响应体。鉴权petstore_auth。HTTP 请求头Content-Type:application/x-www-form-urlencodedAccept:application/xml,application/json源码对应实现lib/api/pet_api.dart 中方法签名为Future updatePetWithForm(int petId, { String name, String status })——petId为必填位置参数name、status为可选命名参数。请求体组装逻辑展示了生成器的通用分支处理当contentType以multipart/form-data开头时构建MultipartRequest并把非空字段写入mp.fields否则本接口走application/x-www-form-urlencoded分支把非空字段写入formParams[name]/formParams[status]。随后在 lib/api_client.dart 中invokeAPI对application/x-www-form-urlencoded类型会直接以formParams作为请求体发送并通过client.post(url, headers: headerParams, body: msgBody)发起请求。uploadFile — 上传宠物图片ApiResponse uploadFile(petId, additionalMetadata, file)为指定宠物上传一张图片同时可附带一段附加元数据属于multipart/form-data上传场景。示例import package:swagger/api.dart; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN; var api_instance new PetApi(); var petId 789; // int | ID of pet to update var additionalMetadata additionalMetadata_example; // String | Additional data to pass to server var file /path/to/file.txt; // MultipartFile | file to upload try { var result api_instance.uploadFile(petId, additionalMetadata, file); print(result); } catch (e) { print(Exception when calling PetApi-uploadFile: $e\n); }参数名称类型描述备注petIdint要更新的宠物 ID必填additionalMetadataString传给服务器的附加数据可选fileMultipartFile要上传的文件可选返回类型ApiResponse鉴权petstore_auth。HTTP 请求头Content-Type:multipart/form-dataAccept:application/json源码对应实现lib/api/pet_api.dart 中uploadFile的contentTypes [multipart/form-data]触发MultipartRequest分支additionalMetadata写入mp.fields[additionalMetadata]file同时设置mp.fields[file] file.field并加入mp.files.add(file)。在 lib/api_client.dart 中当请求体为MultipartRequest时invokeAPI将字段与文件合并进MultipartRequest并通过client.send(request)发送。响应成功后以apiClient.deserialize(response.body, ApiResponse)返回ApiResponse对象可参考模型文档 ApiResponse.md。鉴权配置详解该生成包在 ApiClient 构造函数中预注册了两种鉴权方式名称与 OpenAPI 定义中的 securityScheme 一一对应鉴权名称类型位置对应实现类api_keyAPI KeyHTTP 头参数名api_keyApiKeyAuthpetstore_authOAuth2implicitAuthorization 头Bearer tokenOAuth鉴权应用入口是 lib/api_client.dart 的_updateParamsForAuthinvokeAPI在组装 URL 与请求头之前会遍历authNames取出对应Authentication实例不存在则抛出ArgumentError(Authentication undefined: authName)并调用其applyToParams(queryParams, headerParams)把凭证写入请求。Authentication抽象接口定义于 lib/auth/authentication.dart。OAuth.applyToParamslib/auth/oauth.dart在设置了accessToken时写入headerParams[Authorization] Bearer accessToken即BearerToken 模式。README 中对petstore_auth的完整描述为OAuth、implicit 流、授权 URLhttp://petstore.swagger.io/api/oauth/dialogScope 含write:pets修改账户内宠物与read:pets读取你的宠物。README 还提示可使用 API Keyspecial-key测试鉴权过滤器。底层请求调用链与序列化机制无论调用哪个PetApi方法最终都会汇聚到ApiClient.invokeAPIlib/api_client.dart其执行顺序为_updateParamsForAuth注入鉴权凭证将非空查询参数拼装为?keyvalue...查询串URL 为basePath path queryString合并_defaultHeaderMap与调用方传入的 header并强制写入Content-Type若 body 为MultipartRequest走client.send流式上传否则根据 method 分派client.post/put/delete/patch/get其中application/x-www-form-urlencoded用formParams作为请求体其余类型用serialize(body)即json.encode序列化返回Response。反序列化入口是ApiClient.deserializelib/api_client.dart先去除类型字符串中的空格对String直接返回原文其余类型json.decode后交给_deserialize。_deserialize第 3177 行对内置类型int、bool、double做显式转换对模型类型调用各自的fromJson工厂如Pet.fromJson并通过_RegList/_RegMap正则递归处理List...与MapString,...泛型。任何转换失败都会被包装为ApiException.withInner(500, Exception during deserialization., ...)。以findPetsByStatus为例其返回路径为(apiClient.deserialize(response.body, ListPet) as List).map((item) item as Pet).toList()即先按泛型递归反序列化再映射为ListPet。异常处理约定所有 API 方法在response.statusCode 400时抛出ApiException调用方用try/catch捕获即可。ApiExceptionlib/api_exception.dart携带codeHTTP 状态码、message响应体并支持通过ApiException.withInner保留内部异常与堆栈。其toString()输出格式为ApiException code: message若存在内部异常则追加(Inner exception: ...)及堆栈。此外必填参数缺失时如body null、petId null也会在请求发出前直接抛出ApiException(400, Missing required param: xxx)。Pet 模型参考addPet、updatePet等接口以Pet作为请求/响应模型lib/model/pet.dart。其字段包括int id— 宠物 IDCategory category— 所属分类String name— 宠物名称ListString photoUrls— 图片 URL 列表ListTag tags— 标签列表String status— 商店内宠物状态枚举值为available、pending、sold源码中以注释形式保留枚举见//enum statusEnum { available, pending, sold, };。模型类实现了fromJson/toJson双向转换并提供listFromJson与mapFromJson静态工厂供ApiClient反序列化ListPet、MapString, Pet等类型时调用。完整的字段说明可参考模型文档 Pet.md。延伸阅读本包根目录 README.md包含全部 API 端点索引、模型索引与鉴权说明同包其他 API 文档StoreApi.md订单与库存、UserApi.md用户管理源码入口lib/api.dart库聚合、lib/api_client.dartHTTP 与序列化核心、lib/api/pet_api.dart本指南全部方法的实现该示例的 OpenAPI 定义来源可参考仓库中的 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点击查看免费下载相关推荐3 分钟用会 ShareX一款免费截图工具从截屏到自动上传的完整路径3 分钟用会 ShareX一款免费截图工具从截屏到自动上传的完整路径 ShareX 是一款面向 Windows 的免费开源截图工具与屏幕录制器一键截取屏幕任开发工具代码生成API设计Swagger Codegen 生成 Dart(Jaguar) 客户端PetApi 全量接口调用实战指南Swagger Codegen 生成 Dart Jaguar 客户端PetApi 全量接口调用实战指南 导读 本文以 swagger codegen 仓库中开发工具代码生成API设计掌握 swagger-codegen 生成的 Android HttpClient 版 Petstore 客户端PetApi 完整调用指南掌握 swagger codegen 生成的 Android HttpClient 版 Petstore 客户端PetApi 完整调用指南 本指南以 swag开发工具代码生成API设计创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表