Swagger Codegen 生成 Dart 浏览器客户端Dart Browser Client实战指南【免费下载链接】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 仓库中samples/client/petstore/dart/swagger-browser-client生成样例为核心系统讲解基于 Swagger/OpenAPI 定义生成 Dart 浏览器端 API 客户端后的目录结构、环境要求、依赖安装、认证配置与调用流程并结合 DartClientCodegen.java 源码揭示其生成机制与关键参数。读完本文你将掌握 Dart 浏览器客户端的完整使用链路并了解如何通过生成器参数定制自己的客户端。生成样例概述该样例由 Swagger Codegen 项目中的 Dart 客户端生成器构建包为io.swagger.codegen.languages.DartClientCodegen根据 Petstore 示例定义生成对应 API 版本为 1.0.0。与 Dart 通用客户端不同浏览器客户端browser client在生成时默认开启browserClient选项因此底层 HTTP 层直接使用 Dart 官方package:http中的BrowserClient而非dart:io的HttpClient从而可以在浏览器HTML/JS 环境中直接运行。生成的完整包结构如下位于 swagger-browser-clientlib/ ├── api.dart # 库入口聚合所有 part 文件并暴露 defaultApiClient ├── api_client.dart # ApiClientbasePath、认证注册、invokeAPI 核心实现 ├── api_helper.dart # 序列化 / 反序列化辅助 ├── api_exception.dart # ApiException 异常类型 ├── api/ │ ├── pet_api.dart # PetApi │ ├── store_api.dart # StoreApi │ └── user_api.dart # UserApi ├── auth/ │ ├── authentication.dart # Authentication 接口 │ ├── api_key_auth.dart # ApiKeyAuthheader / query │ ├── http_basic_auth.dart # HttpBasicAuth │ └── oauth.dart # OAuthBearer Token └── model/ ├── amount.dart # Amount ├── api_response.dart # ApiResponse ├── category.dart # Category ├── currency.dart # Currency ├── order.dart # Order ├── pet.dart # Pet ├── tag.dart # Tag └── user.dart # User docs/ # 各 API / Model 的 Markdown 文档 pubspec.yaml # 包定义name: swagger, version: 1.0.0 git_push.sh # 推送脚本入口文件 api.dart 顶部即可看到浏览器客户端的关键特征import package:http/browser_client.dart; import package:http/http.dart;它通过part机制将api_client.dart、auth/与各 API、Model 聚合进swagger.api库并导出全局单例defaultApiClient默认指向http://petstore.swagger.io/v2。环境要求Requirements根据样例 README 的说明使用该客户端需要满足Dart 1.20.0 或更高版本或Flutter 0.0.20 或更高版本在 Flutter Web / 移动端项目中也可复用同一套代码。注意该样例生成于较早期的 Dart 版本语法如new Pet()、new ApiClient()在较新 SDK 上仍可运行但建议按项目实际 Dart SDK 版本做必要的 lint 适配。安装与依赖配置Installation Usage客户端以 Dart 包形式发布可通过两种方式引入你的项目二者都需要在项目根目录的pubspec.yaml中声明依赖。通过 Git 依赖引入发布到 GitHub 时若该 Dart 包发布到了 GitHub 仓库在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其中GIT_USER_ID与GIT_REPO_ID是发布时的占位符实际使用时需替换为真实仓库的属主与仓库名。注意 Dart 的 pubspec 中git依赖不支持在子字段直接写version更规范的写法是将版本约束放在 git 依赖之外例如dependencies: swagger: git: url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git通过本地路径依赖引入本地开发调试时使用path依赖直接指向生成的包目录dependencies: swagger: path: /path/to/swagger将/path/to/swagger替换为实际生成的客户端目录即本样例所在的 swagger-browser-client 目录即可。生成包自身的 pubspec.yaml 只声明了一个运行时依赖name: swagger version: 1.0.0 description: Swagger API client dependencies: http: 0.11.1 0.12.0即浏览器客户端必须依赖http包版本范围为0.11.1 0.12.0它提供了BrowserClient实现。快速开始调用 PetApiREADME 给出了最小可用示例——调用addPet新增一只宠物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); }对应的底层实现位于 pet_api.dartPetApi构造函数接受可选的ApiClient缺省使用defaultApiClientaddPet会先校验必填参数body为空则抛出ApiException(400, Missing required param: body)然后构建路径/pet、声明contentTypes [application/json,application/xml]与authNames [petstore_auth]最后调用apiClient.invokeAPI(path, POST, ...)发起请求响应状态码大于等于 400 时抛出ApiException。自定义 basePath 与全局头实际接入时通常需要把请求指向自己的服务端可通过构造参数覆盖默认的http://petstore.swagger.io/v2或为所有请求添加公共头见 api_client.dartvar client new ApiClient(basePath: https://your-api.example.com/v2); client.addDefaultHeader(X-Custom-Header, value); var api_instance new PetApi(client);invokeAPI方法内部会依次完成应用认证参数_updateParamsForAuth、拼接 query string、合并默认头与Content-Type并对multipart/form-data请求使用MultipartRequest发送普通请求则按 POST/PUT/DELETE/PATCH 分发默认走 GET。API 端点一览所有 URIs 均相对于http://petstore.swagger.io/v2。完整端点表如下各方法的详细参数与返回值见 docs/PetApi.md、docs/StoreApi.md、docs/UserApi.mdPetApi方法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 imageStoreApi方法HTTP 请求描述deleteOrderDELETE/store/order/{orderId}Delete purchase order by IDgetInventoryGET/store/inventoryReturns pet inventories by statusgetOrderByIdGET/store/order/{orderId}Find purchase order by IDplaceOrderPOST/store/orderPlace an order for a petUserApi方法HTTP 请求描述createUserPOST/userCreate usercreateUsersWithArrayInputPOST/user/createWithArrayCreates list of users with given input arraycreateUsersWithListInputPOST/user/createWithListCreates list of users with given input arraydeleteUserDELETE/user/{username}Delete usergetUserByNameGET/user/{username}Get user by user nameloginUserGET/user/loginLogs user into the systemlogoutUserGET/user/logoutLogs out current logged in user sessionupdateUserPUT/user/{username}Updated user数据模型Models生成的模型类与 Swagger 定义一一对应均提供fromJson/toJson能力用于ApiClient的自动序列化与反序列化AmountApiResponseCategoryCurrencyOrderPetTagUser类型映射规则可以从生成器源码中得到印证DartClientCodegen.javaarray/List→Listboolean→boolstring/char/UUID/binary/ByteArray→Stringlong/short/integer→intnumber→numfloat/double→doubleDate/date→DateTimeFile→MultipartFileobject→Object。ApiClient._deserialize中的 switch 分支即依据这些映射把 JSON 还原为模型实例并支持ListT、MapString,T的递归反序列化。认证Authorization该样例定义了两类认证ApiClient构造时已按名称注册见 api_client.dart请求时会根据每个操作声明的authNames自动附加认证信息。api_keyAPI Key类型API key参数名api_key位置HTTP Header对应实现为 api_key_auth.dart 中的ApiKeyAuth支持 header 与 query 两种位置若设置了apiKeyPrefix会以$apiKeyPrefix $apiKey的形式拼接后写入头。使用方式((defaultApiClient.getAuthentication(api_key)) as ApiKeyAuth).apiKey special-key;Petstore 示例中special-key即用于测试该认证过滤器的样例 Key。petstore_authOAuth 2.0类型OAuth流程implicit隐式授权授权 URLhttp://petstore.swagger.io/api/oauth/dialogScopeswrite:petsmodify pets in your accountread:petsread your pets对应实现为 oauth.dart 中的OAuth类它在applyToParams中将accessToken以Authorization: Bearer token的形式写入请求头。设置方式((defaultApiClient.getAuthentication(petstore_auth)) as OAuth).setAccessToken(YOUR_ACCESS_TOKEN);由于采用隐式授权流程token 通常由前端 OAuth 流程如重定向回跳携带 access_token获取后注入客户端README 中的注释示例//swagger.api.Configuration.accessToken YOUR_ACCESS_TOKEN;即为这一步骤的占位提示。生成器参数如何定制 Dart 浏览器客户端该样例的生成行为由 DartClientCodegen.java 控制生成器暴露了以下 CLI 选项CliOption可通过swagger-codegen generate -Dxxx...或配置文件定制参数默认值说明browserClienttrue是否生成浏览器客户端。默认为true即默认产物即为本文所述的 BrowserClient 版本设为false时改用基于dart:io的 HttpClient 版本pubNameswagger生成的pubspec.yaml中的包名name字段pubVersion1.0.0生成的包版本号pubDescriptionSwagger API client生成的包描述useEnumExtensionfalse是否启用x-enum-values扩展来生成枚举开启后通过buildEnumFromVendorExtension读取 vendor extension 构建枚举成员sourceFolder空生成代码的源码根目录影响lib/等目录的生成位置在processOpts()中生成器按上述参数依次写入模板属性并通过SupportingFile一次性生成pubspec.yaml、.analysis_options、api_client.dart、api_exception.dart、api_helper.dart、api.dart、auth/下 4 个认证文件、git_push.sh、.gitignore与README.mdDartClientCodegen.java。API 与 Model 源文件则由api.mustache、model.mustache模板生成文档由api_doc.mustache、object_doc.mustache生成。命名规范化方面生成器会把 operationId 驼峰化为方法名保留字前加call_前缀、变量名做-转_与首字母小写驼峰处理DartClientCodegen.java这些规则直接决定了你看到的addPet、findPetsByStatus等 API 形态。小结swagger-browser-client样例展示了 Swagger Codegen 产出 Dart 浏览器客户端的标准形态以pubspec.yaml声明依赖、以lib/api.dart聚合全部 API 与 Model、以ApiClient统一处理 basePath、认证与 HTTP 调用。理解其目录结构、安装方式、认证注入机制以及DartClientCodegen的可调参数后你可以基于同一份 OpenAPI/Swagger 定义快速生成并定制出符合自身业务需要的 Dart 浏览器端 SDK。【免费下载链接】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创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考