API · SDK
配置 API 客户端和 SDK
将基础 URL 移出代码,指向真实服务,并添加一项检查,防止示例地址进入生产环境。
指南 · Swagger Petstore
Swagger Petstore 是无数 Swagger UI 和 OpenAPI 教程背后的示例 API,它并不在 example-petstore.com 上。本指南列出它的真实地址,给出可用的请求示例,并说明在公共版本不好用时如何运行自己的副本。
SmartBear 旗下的 API 工具 Swagger 运行着两个公共版本的 Petstore,两者提供相同的资源:宠物、订单和用户。
| 版本 | 请求的基础 URL | API 描述与 Swagger UI |
|---|---|---|
| Petstore 3 (OpenAPI 3.0) | https://petstore3.swagger.io/api/v3 | openapi.json · petstore3.swagger.io |
| Petstore (Swagger 2.0) | https://petstore.swagger.io/v2 | swagger.json · petstore.swagger.io |
新项目最好使用 Petstore 3:它遵循当前工具和代码生成器所预期的 OpenAPI 3.0 规范。Swagger 2.0 版本仍可访问,并出现在较早的教程中。
以下是几个 curl 请求示例。只要把基础 URL 设为上面的某个地址,同样的路径也适用于 Postman、Insomnia 或生成的客户端。
# 状态为 "available" 的宠物
curl -H "Accept: application/json" "https://petstore3.swagger.io/api/v3/pet/findByStatus?status=available"
# 添加一只宠物(name 和 photoUrls 为必填)
curl -X POST "https://petstore3.swagger.io/api/v3/pet" \
-H "Content-Type: application/json" \
-d '{"id": 12345, "name": "doggie", "photoUrls": [], "status": "available"}'
# 按状态统计库存(使用测试密钥)
curl -H "api_key: special-key" "https://petstore.swagger.io/v2/store/inventory"
用 PHP 和 Guzzle 实现同样的请求:
// PHP, Guzzle:状态为 "available" 的宠物
$client = new GuzzleHttp\Client(['base_uri' => 'https://petstore3.swagger.io/api/v3/']);
$response = $client->get('pet/findByStatus', ['query' => ['status' => 'available']]);
$pets = json_decode((string) $response->getBody(), true);
主要路径:/pet、/pet/findByStatus、/pet/findByTags、/pet/{petId}、/store/inventory、/store/order、/user、/user/login 和 /user/logout。
Petstore 演示了两种安全方案:放在 api_key 请求头中的 API 密钥,以及 OAuth 2.0 流程(petstore_auth)。Swagger 2.0 描述中给出了用于测试授权过滤器的密钥 special-key。这些都是演示用凭据:切勿在 Petstore 上尝试真实的密钥、令牌或密码。
Petstore 是开源软件(Apache 2.0)。使用 Docker 只需一条命令:
docker run -d --name petstore -p 8080:8080 swaggerapi/petstore3
# Swagger UI: http://localhost:8080
# API 描述: http://localhost:8080/api/v3/openapi.json
# 基础 URL: http://localhost:8080/api/v3
不使用 Docker 时,克隆 swagger-api/swagger-petstore,然后用 mvn package jetty:run 启动(同样在 8080 端口)。自己的副本每次运行时都以相同的内置示例数据(十只宠物,外加若干订单和用户)开始,因此测试每次的表现都一致。
OpenAPI 规范仓库中的示例文件 petstore.yaml 把 http://petstore.swagger.io/v1 列为服务器,路径为 /pets。该文件只用于说明规范,背后并没有运行中的服务。由它生成的客户端会收到 404 Not Found。请改为指向 https://petstore3.swagger.io/api/v3 或自己的副本;由于路径不同(是 /pet 而不是 /pets),请用 Petstore 3 的 openapi.json 重新生成客户端。
example-petstore.com 是另一个名称:它是 Google 关于 Analytics 和搜索的文档中使用的示例域名,这里没有 API。发往此域名上 /v2/pet 等路径的请求会收到 410 Gone,并附有 JSON 格式的说明。
.env 文件、Postman 环境或 OpenAPI 描述中 servers 字段里的基础 URL,把 example-petstore.com 替换为上面的某个地址。