拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Swagger Codegen 生成 Dart Flutter 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 为 Petstore 示例规范生成的 Dart/Flutter 客户端中PetApi类的完整使用指南适用于通过swagger-codegen生成 Dart 语言 API 客户端后在 Flutter 项目中对接 Petstore 宠物资源场景。读完本文你将掌握PetApi全部 8 个端点新增、删除、查询、更新、上传的调用方式、参数与返回类型、petstore_authOAuth2与api_keyAPI Key两种授权的配置方法以及生成客户端底层ApiClient.invokeAPI的请求拼接与反序列化原理。文档背景与生成来源本文所讲解的PetApi文档位于仓库的生成样例目录samples/client/petstore/dart/flutter_petstore/swagger/docs/PetApi.md它并不是手写文档而是由 Swagger Codegen 依据 Petstore 的 OpenAPI/Swagger 定义自动生成的 Dart 客户端文档。同目录下的 swagger/README.md 明确说明API 版本1.0.0构建包io.swagger.codegen.languages.DartClientCodegen生成代码要求 Dart 1.20.0 或以上、Flutter 0.0.20 或以上因此本文的每一个方法签名、参数表、授权说明与 HTTP 请求头信息都是生成器从规范文件映射出来的真实契约可直接在对应的生成源码 lib/api/pet_api.dart 中得到印证。快速上手加载包与调用第一个接口所有 URI 默认相对于http://petstore.swagger.io/v2这一 basePath。首先在 Dart/Flutter 代码中导入生成的 API 包import package:swagger/api.dart;包内通过 lib/api.dart 将 API 客户端、认证器、模型全部以part的方式组合进单一库swagger.api并导出全局默认客户端defaultApiClientApiClient defaultApiClient new ApiClient();PetApi的构造函数允许注入自定义的ApiClient不传时使用默认客户端默认 basePath 为http://petstore.swagger.io/v2class PetApi { final ApiClient apiClient; PetApi([ApiClient apiClient]) : apiClient apiClient ?? defaultApiClient; }如果服务地址与默认 basePath 不一致可在创建客户端时指定var apiClient new ApiClient(basePath: https://your-host.example.com/v2); var api new PetApi(apiClient);安装方式pubspec.yaml 引用该生成包作为独立 Dart 包swagger版本 1.0.0见 pubspec.yaml依赖http: 0.11.1 0.12.0。若发布到 Git 仓库可在项目pubspec.yaml中加入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若在本地开发调试则使用path引用dependencies: swagger: path: /path/to/swaggerAPI 端点总览PetApi共封装 8 个 HTTP 端点覆盖 Petstore 宠物资源的增删改查与图片上传映射关系如下与 README.md 一致方法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其中addPet/updatePet以 JSON/XML 请求体提交完整Pet对象deletePet/getPetById/updatePetWithForm以路径参数{petId}定位资源findPetsByStatus/findPetsByTags以查询字符串过滤uploadFile使用multipart/form-data上传图片。下方按端点逐一展开。认证与授权配置在调用前需要先完成授权配置PetApi涉及的两种认证方式均定义在生成包的认证目录 lib/auth 下。petstore_authOAuth2implicit 流程用于addPet、deletePet、findPetsByStatus、findPetsByTags、updatePet、updatePetWithForm、uploadFile。按文档注释配置访问令牌// TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN;配置信息来源 README.md类型OAuthFlowimplicit授权 URLhttp://petstore.swagger.io/api/oauth/dialog作用域write:petsmodify pets in your account、read:petsread your pets从源码看lib/auth/oauth.dart 的OAuth实现会在accessToken非空时向请求头写入Authorization: Bearer tokenvoid applyToParams(ListQueryParam queryParams, MapString, String headerParams) { if (accessToken ! null) { headerParams[Authorization] Bearer accessToken; } }api_keyAPI Key位于 HTTP Header仅用于getPetById。按文档注释配置 API Key 及可选前缀// 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;配置信息来源 README.md类型API key参数名api_key位置HTTP header在 lib/auth/api_key_auth.dart 中ApiKeyAuth依据构造时传入的locationheader或query与paramName将 key 写入请求头或查询串当设置了apiKeyPrefix时最终值为$apiKeyPrefix $apiKey。这两种认证器在ApiClient构造函数中按名字注册_authentications[api_key] new ApiKeyAuth(header, api_key); _authentications[petstore_auth] new OAuth();端点详解addPetaddPet(body)—— Add a new pet to the storeimport 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); }参数名称类型说明备注bodyPetPet object that needs to be added to the store必填返回类型void空响应体授权petstore_authHTTP 请求头Content-Typeapplication/json, application/xmlAcceptapplication/xml, application/json从 pet_api.dart 源码看addPet将body作为postBody发送contentTypes取第一个元素application/json作为实际 Content-Type认证名authNames [petstore_auth]请求方法为POST路径/pet。若body为空则直接抛出ApiException(400, Missing required param: body)。deletePetdeletePet(petId, apiKey)—— Deletes a petimport 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); }参数名称类型说明备注petIdintPet id to delete必填apiKeyString可选返回类型void空响应体授权petstore_authHTTP 请求头Content-TypeNot definedAcceptapplication/xml, application/json源码实现中路径变量通过replaceAll({petId}, petId.toString())完成模板替换并执行headerParams[api_key] apiKey将可选参数写入请求头该方法同时声明 OAuth 认证。返回空响应。findPetsByStatusListPet findPetsByStatus(status)—— Finds Pets by status支持以逗号分隔的多个状态值。状态取值参考 Pet 模型 中status属性的枚举注释available、pending、sold。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); }参数名称类型说明备注statusListStringStatus values that need to be considered for filter必填返回类型ListPet授权petstore_authHTTP 请求头Content-TypeNot definedAcceptapplication/xml, application/json这是生成客户端演示集合参数序列化的典型例子源码调用_convertParametersForCollectionFormat(csv, status, status)将ListString编码为查询参数。参照 lib/api_helper.dart默认或显式csv格式使用逗号,连接为单个查询参数multi格式则为每个元素生成同名参数ssv空格、tsv制表符、pipes|分别对应不同分隔符。响应通过apiClient.deserialize(response.body, ListPet)反序列化为Pet列表。findPetsByTagsListPet findPetsByTags(tags)—— Finds Pets by 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); }参数名称类型说明备注tagsListStringTags to filter by必填返回类型ListPet授权petstore_authHTTP 请求头Content-TypeNot definedAcceptapplication/xml, application/json与findPetsByStatus实现对称以csv集合格式把tags编码进查询字符串返回ListPet。此类按标签过滤接口在真实 API 中往往成本较高生产环境通常以分页与缓存策略配合使用但生成客户端的调用契约与上面完全一致。getPetByIdPet getPetById(petId)—— Find pet by IDReturns a single petimport 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); }参数名称类型说明备注petIdintID of pet to return必填返回类型Pet授权api_keyHTTP 请求头Content-TypeNot definedAcceptapplication/xml, application/json这是PetApi中唯一使用api_keyHTTP Header 中的api_key参数认证的方法源码中authNames [api_key]。响应经apiClient.deserialize(response.body, Pet) as Pet转为Pet对象HTTP 状态码 400 时抛出ApiException(response.statusCode, response.body)body为空时返回null。updatePetupdatePet(body)—— Update an existing petimport 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); }参数名称类型说明备注bodyPetPet object that needs to be added to the store必填返回类型void空响应体授权petstore_authHTTP 请求头Content-Typeapplication/json, application/xmlAcceptapplication/xml, application/json源码中updatePet与addPet几乎同构仅请求方法不同PUTvsPOST同样要求body非空否则抛出ApiException(400, Missing required param: body)。contentTypes首个值application/json决定实际请求体的编码方式。updatePetWithFormupdatePetWithForm(petId, name, status)—— Updates a pet in the store with form dataimport 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); }参数名称类型说明备注petIdintID of pet that needs to be updated必填nameStringUpdated name of the pet可选statusStringUpdated status of the pet可选返回类型void空响应体授权petstore_authHTTP 请求头Content-Typeapplication/x-www-form-urlencodedAcceptapplication/xml, application/json源码将该方法声明为updatePetWithForm(int petId, { String name, String status })可选参数以命名参数呈现非空的name、status经parameterToString序列化后写入formParamscontentType为application/x-www-form-urlencodedApiClient.invokeAPI会据此以formParams作为请求体参见下文底层调用链。uploadFileApiResponse uploadFile(petId, additionalMetadata, file)—— uploads an imageimport 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); }参数名称类型说明备注petIdintID of pet to update必填additionalMetadataStringAdditional data to pass to server可选fileMultipartFilefile to upload可选返回类型ApiResponse授权petstore_authHTTP 请求头Content-Typemultipart/form-dataAcceptapplication/json这是唯一的文件上传端点。源码中当contentType以multipart/form-data开头时构造MultipartRequest将additionalMetadata放入mp.fields将file的字段名与文件分别加入mp.fields[file]与mp.files。ApiClient.invokeAPI检测到body is MultipartRequest后改用client.send(request)发送 multipart 请求并流式读取响应。返回值ApiResponse通常携带code、type与message字段用于标识上传结果。底层调用链PetApi 如何发出一次请求所有端点最终都汇聚到 lib/api_client.dart 的invokeAPI理解这条链路有助于排查请求问题路径模板替换{petId}等路径变量通过replaceAll替换为参数值如 pet_api.dart 中/pet/{petId}.replaceAll({petId}, petId.toString())。查询参数编码_convertParametersForCollectionFormat负责集合参数csv/ssv/tsv/pipes/multi的序列化非集合参数直接namevalue。认证注入_updateParamsForAuth遍历authNames从_authentications取出对应认证器并调用applyToParams将 API Key 或 Bearer Token 写入 header/query。URL 组装basePath path queryString随后合并默认头并设置Content-Type。请求分派MultipartRequest走client.send普通请求依据 HTTP 方法POST/PUT/DELETE/PATCH/GET分别调用client.post/put/delete/patch/get其中application/x-www-form-urlencoded时 body 取formParams否则对postBody执行serialize即json.encode。响应反序列化deserialize(response.body, ListPet)等调用基于正则^List(.*)$、^MapString,(.*)$递归解析泛型基本类型String/int/bool/double直接转换模型类型调用Pet.fromJson、ApiResponse.fromJson等工厂方法。错误处理状态码 400 时抛出 ApiException其中携带code、message并可通过withInner保留反序列化等内部异常与堆栈。Pet 模型与关联文档导航PetApi的多数方法都涉及Pet模型见 docs/Pet.md 与 lib/model/pet.dart其字段契约如下名称类型说明备注idint可选默认 nullcategoryCategory可选默认 nullnameString必填默认 nullphotoUrlsListString默认 []tagsListTag可选默认 []statusStringpet status in the store可选默认 null枚举available/pending/soldPet模型提供fromJson、toJson、listFromJson、mapFromJson静态工厂用于与 JSON 相互转换。uploadFile返回的 ApiResponse 模型同样在生成包内定义。若要进一步浏览整个客户端可参考生成包入口 swagger/README.md其中还包含StoreApi订单与库存与UserApi用户体系的端点清单、全部模型文档以及两种授权方式的详细说明。常见问题与注意事项认证顺序getPetById使用api_key其余 7 个方法使用petstore_auth混用时注意分别为两种认证器赋值避免请求缺少鉴权头导致 401。必填参数校验生成代码在方法入口即对必填参数判空缺失时抛出ApiException(400, Missing required param: xxx)而不是等到网络请求阶段才报错。集合参数格式findPetsByStatus/findPetsByTags默认以csv编码若规范声明collectionFormat: multi生成代码会输出同名多个查询参数二者不可混用。文件上传uploadFile的file必须构造为MultipartFile仅传文件路径字符串无法完成上传该端点 Accept 仅为application/json。basePath 定制默认指向http://petstore.swagger.io/v2对接自有环境时通过ApiClient(basePath: ...)注入。综上PetApi作为 Swagger Codegen 生成的 Dart 客户端范例完整演示了从路径模板、查询/表单参数、multipart 上传到双认证体系的一整套请求链路。把握这份文档与源码的对应关系你就可以在自己的 Flutter 项目中熟练驾驭生成客户端并以此类推掌握StoreApi、UserApi以及任意 Swagger/OpenAPI 规范生成的 Dart 包。赞分享开发工具代码生成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 中 Amount 模型的 Dart 客户端生成解析以 dart-jaguar Flutter Petstore 为例swagger codegen 中 Amount 模型的 Dart 客户端生成解析以 dart jaguar Flutter Petstore 为例 导读 本开发工具代码生成API设计Swagger Codegen 生成的 Dart/Jaguar UserApi 客户端使用指南Flutter Petstore 示例Swagger Codegen 生成的 Dart/Jaguar UserApi 客户端使用指南Flutter Petstore 示例 导读 本文以 swag开发工具代码生成API设计Swagger Codegen 生成 Dart/Jaguar 客户端 PetApi 全面使用指南Swagger Codegen 生成 Dart/Jaguar 客户端 PetApi 全面使用指南 导读 本指南以 Swagger Codegen 的 Dart开发工具代码生成API设计创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门