swagger-codegen 生成 Dart 浏览器客户端 PetApi 完整指南:Petstore 宠物接口调用实战
2026/9/23 9:44:33 网站建设 项目流程
  • 开发工具
  • 代码生成
  • API设计

【免费下载链接】swagger-codegen

swagger-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:httpBrowserClient(见 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中,使用时只需一条 import:

import 'package:swagger/api.dart';

lib/api.dart 通过part指令把api_client.dartapi_helper.dartapi_exception.dart、三个 auth 实现(authentication.dartapi_key_auth.dartoauth.darthttp_basic_auth.dart)、三个 API 类(pet_api.dartstore_api.dartuser_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_auth(OAuth2,implicit 流,授权 URLhttp://petstore.swagger.io/api/oauth/dialog,Scope 包括write:petsread:pets)。

HTTP 请求头

  • Content-Type:application/json,application/xml
  • Accept: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必填
apiKeyString(header 参数)可选

返回类型

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 — 按状态查找宠物

List<Pet> 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 = []; // List<String> | 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"); }

参数

名称类型描述备注
statusList<String>需要参与筛选的状态值必填

返回类型

List<Pet>

鉴权

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, 'List<Pet>')后逐项映射为Pet对象列表。

findPetsByTags — 按标签查找宠物

List<Pet> 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 = []; // List<String> | Tags to filter by try { var result = api_instance.findPetsByTags(tags); print(result); } catch (e) { print("Exception when calling PetApi->findPetsByTags: $e\n"); }

参数

名称类型描述备注
tagsList<String>用于过滤的标签必填

返回类型

List<Pet>

鉴权

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_key(API 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类实现:构造时传入locationheaderquery)与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/xml
  • Accept: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-urlencoded
  • Accept:application/xml,application/json

源码对应实现

lib/api/pet_api.dart 中,方法签名为Future updatePetWithForm(int petId, { String name, String status })——petId为必填位置参数,namestatus为可选命名参数。请求体组装逻辑展示了生成器的通用分支处理:

  • contentTypemultipart/form-data开头时,构建MultipartRequest并把非空字段写入mp.fields
  • 否则(本接口走application/x-www-form-urlencoded分支),把非空字段写入formParams['name']/formParams['status']

随后在 lib/api_client.dart 中,invokeAPIapplication/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-data
  • Accept:application/json

源码对应实现

lib/api/pet_api.dart 中,uploadFilecontentTypes = ["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_keyApiKeyAuth
petstore_authOAuth2(implicit)Authorization 头(Bearer <token>OAuth

鉴权应用入口是 lib/api_client.dart 的_updateParamsForAuthinvokeAPI在组装 URL 与请求头之前,会遍历authNames,取出对应Authentication实例(不存在则抛出ArgumentError("Authentication undefined: " + authName)),并调用其applyToParams(queryParams, headerParams)把凭证写入请求。Authentication抽象接口定义于 lib/auth/authentication.dart。

OAuth.applyToParams(lib/auth/oauth.dart)在设置了accessToken时写入headerParams["Authorization"] = "Bearer " + accessToken,即BearerToken 模式。README 中对petstore_auth的完整描述为:OAuth、implicit 流、授权 URLhttp://petstore.swagger.io/api/oauth/dialog,Scope 含write:pets(修改账户内宠物)与read:pets(读取你的宠物)。README 还提示:可使用 API Keyspecial-key测试鉴权过滤器。

底层请求调用链与序列化机制

无论调用哪个PetApi方法,最终都会汇聚到ApiClient.invokeAPI(lib/api_client.dart),其执行顺序为:

  1. _updateParamsForAuth注入鉴权凭证;
  2. 将非空查询参数拼装为?key=value&...查询串,URL 为basePath + path + queryString
  3. 合并_defaultHeaderMap与调用方传入的 header,并强制写入Content-Type
  4. 若 body 为MultipartRequestclient.send流式上传;否则根据 method 分派client.post/put/delete/patch/get,其中application/x-www-form-urlencodedformParams作为请求体,其余类型用serialize(body)(即json.encode)序列化;
  5. 返回Response

反序列化入口是ApiClient.deserialize(lib/api_client.dart):先去除类型字符串中的空格,对'String'直接返回原文,其余类型json.decode后交给_deserialize_deserialize(第 31~77 行)对内置类型(intbooldouble)做显式转换,对模型类型调用各自的fromJson工厂(如Pet.fromJson),并通过_RegList/_RegMap正则递归处理List<...>Map<String,...>泛型。任何转换失败都会被包装为ApiException.withInner(500, 'Exception during deserialization.', ...)

findPetsByStatus为例,其返回路径为(apiClient.deserialize(response.body, 'List<Pet>') as List).map((item) => item as Pet).toList(),即先按泛型递归反序列化,再映射为List<Pet>

异常处理约定

所有 API 方法在response.statusCode >= 400时抛出ApiException,调用方用try/catch捕获即可。ApiException(lib/api_exception.dart)携带code(HTTP 状态码)、message(响应体),并支持通过ApiException.withInner保留内部异常与堆栈。其toString()输出格式为ApiException <code>: <message>,若存在内部异常则追加(Inner exception: ...)及堆栈。此外,必填参数缺失时(如body == nullpetId == null)也会在请求发出前直接抛出ApiException(400, "Missing required param: xxx")

Pet 模型参考

addPetupdatePet等接口以Pet作为请求/响应模型(lib/model/pet.dart)。其字段包括:

  • int id— 宠物 ID;
  • Category category— 所属分类;
  • String name— 宠物名称;
  • List<String> photoUrls— 图片 URL 列表;
  • List<Tag> tags— 标签列表;
  • String status— 商店内宠物状态,枚举值为availablependingsold(源码中以注释形式保留枚举,见//enum statusEnum { available, pending, sold, };)。

模型类实现了fromJson/toJson双向转换,并提供listFromJsonmapFromJson静态工厂,供ApiClient反序列化List<Pet>Map<String, Pet>等类型时调用。完整的字段说明可参考模型文档 Pet.md。

延伸阅读

  • 本包根目录 README.md:包含全部 API 端点索引、模型索引与鉴权说明;
  • 同包其他 API 文档:StoreApi.md(订单与库存)、UserApi.md(用户管理);
  • 源码入口:lib/api.dart(库聚合)、lib/api_client.dart(HTTP 与序列化核心)、lib/api/pet_api.dart(本指南全部方法的实现);
  • 该示例的 OpenAPI 定义来源可参考仓库中的 petstore 相关规格文件。
  • 开发工具
  • 代码生成
  • API设计

【免费下载链接】swagger-codegen

swagger-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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询