Rest Graphql Debug
调试 REST/GraphQL API:状态码、身份验证、架构、复现。
技能元数据
| 来源 | 可选 — 使用 hermes skills install official/software-development/rest-graphql-debug 安装 |
| 路径 | optional-skills/software-development/rest-graphql-debug |
| 版本 | 1.2.0 |
| 作者 | eren-karakus0 |
| 许可证 | MIT |
| 标签 | api, rest, graphql, http, debugging, testing, curl, integration |
| 相关技能 | systematic-debugging, test-driven-development |
参考:完整 SKILL.md
以下是 Hermes 在触发此技能时加载的完整技能定义。这是技能激活时代理看到的指令。
API 测试与调试
通过 Hermes 工具驱动 REST 和 GraphQL 诊断 — 使用 terminal 执行 curl,使用 execute_code 执行 Python requests,使用 web_extract 获取供应商文档。在猜测修复方案之前,先隔离出故障层。
何时使用
- API 返回意外的状态码或响应体
- 身份验证失败(刷新令牌后出现 401/403、OAuth、API 密钥)
- 在 Postman 中有效但在代码中失败
- Webhook / 回调集成调试
- 构建或审查 API 集成测试
- 速率限制或分页问题
如果是 UI 渲染、数据库查询调优或 DNS/防火墙基础设施问题,请跳过(升级处理)。
核心原则
隔离层级,然后修复。 200 OK 可能隐藏了损坏的数据。500 错误可能掩盖了一个字符的身份验证拼写错误。按顺序检查整个链路;切勿跳过任何步骤。
1. Connectivity → can we reach the host at all?
1.5 Timeouts → connect-slow vs read-slow?
2. TLS/SSL → cert valid and trusted?
3. Auth → credentials correct and unexpired?
4. Request format → payload shape match server expectations?
5. Response parse → does our code accept what came back?
6. Semantics → does the data mean what we assume?
5 分钟快速入门
通过终端使用 REST
# Verbose request/response exchange
terminal('curl -v https://api.example.com/users/1')
# POST with JSON
terminal("""curl -X POST https://api.example.com/users \\
-H 'Content-Type: application/json' \\
-H "Authorization: Bearer $TOKEN" \\
-d '{"name":"test","email":"test@example.com"}'""")
# Headers only
terminal('curl -sI https://api.example.com/health')
# Pretty-print JSON
terminal('curl -s https://api.example.com/users | python3 -m json.tool')
通过终端使用 GraphQL
terminal("""curl -X POST https://api.example.com/graphql \\
-H 'Content-Type: application/json' \\
-H "Authorization: Bearer $TOKEN" \\
-d '{"query":"{ user(id: 1) { name email } }"}'""")
GraphQL 陷阱: 即使查询失败,服务器通常也会返回 HTTP 200。无论状态码如何,务必检查 errors 字段:
execute_code('''
import os, requests
resp = requests.post(
"https://api.example.com/graphql",
json={"query": "{ user(id: 1) { name email } }"},
headers={"Authorization": f"Bearer {os.environ['TOKEN']}"},
timeout=10,
)
data = resp.json()
if data.get("errors"):
for err in data["errors"]:
print(f"GraphQL error: {err['message']} (path: {err.get('path')})")
print(data.get("data"))
''')
通过 execute_code 使用 Python (requests)
execute_code('''
import requests
resp = requests.get(
"https://api.example.com/users/1",
headers={"Authorization": "Bearer <TOKEN>"},
timeout=(3.05, 30), # (connect, read)
)
print(resp.status_code, dict(resp.headers))
print(resp.text[:500])
''')
分层调试流程
第 1 步 — 连通性
terminal('nslookup api.example.com')
terminal('curl -v --connect-timeout 5 https://api.example.com/health')
故障原因:DNS 无法解析、防火墙、需要 VPN、缺少代理。
第 1.5 步 — 超时
区分无法到达与能到达但缓慢:
terminal('''curl -w "dns:%{time_namelookup}s connect:%{time_connect}s tls:%{time_appconnect}s ttfb:%{time_starttransfer}s total:%{time_total}s\\n" \\
-o /dev/null -s https://api.example.com/endpoint''')
在 Python 中,始终传递元组形式的超时参数 — requests 没有默认值,否则会无限挂起:
execute_code('''
import requests
from requests.exceptions import ConnectTimeout, ReadTimeout
try:
requests.get(url, timeout=(3.05, 30))
except ConnectTimeout:
print("Cannot reach host — DNS, firewall, VPN")
except ReadTimeout:
print("Connected but server is slow")
''')
诊断:高 time_connect 表示网络/防火墙问题;低 time_connect 但高 time_starttransfer 表示服务器响应缓慢。
第 2 步 — TLS/SSL
terminal('curl -vI https://api.example.com 2>&1 | grep -E "SSL|subject|expire|issuer"')
故障原因:证书过期、自签名证书、主机名不匹配、缺少 CA bundle。仅在临时调试时使用 -k,切勿在生产代码中使用。
第 3 步 — 身份验证
# Token validity check
terminal('curl -s -o /dev/null -w "%{http_code}\\n" -H "Authorization: Bearer $TOKEN" https://api.example.com/me')
# Decode JWT exp claim — handles base64url padding correctly
execute_code('''
import json, base64, os
tok = os.environ["TOKEN"]
payload = tok.split(".")[1]
payload += "=" * (-len(payload) % 4)
print(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2))
''')
检查清单:
- 令牌是否过期?(JWT 中的
exp声明) - 方案是否正确?Bearer vs Basic vs Token vs
X-Api-Key - 环境是否正确?在生产环境使用 staging 密钥是常见错误
- API 密钥是在请求头中还是查询参数中(
?api_key=…)?
第 4 步 — 请求格式
terminal("""curl -v -X POST https://api.example.com/endpoint \\
-H 'Content-Type: application/json' \\
-d '{"key":"value"}' 2>&1""")
Content-Type / 请求体不匹配 — 静默的 415/400 错误:
# WRONG — data= sends form-encoded, header lies
requests.post(url, data='{"k":"v"}', headers={"Content-Type": "application/json"})
# RIGHT — json= auto-sets header AND serializes
requests.post(url, json={"k": "v"})
# WRONG — Accept says XML, code calls .json()
requests.get(url, headers={"Accept": "text/xml"})
# RIGHT — let requests build multipart with boundary
requests.post(url, files={"file": open("doc.pdf", "rb")})
常见问题:表单编码与 JSON 混淆、缺少必填字段、HTTP 方法错误、查询参数未编码。
第 5 步 — 响应解析
在调用 .json() 之前始终检查 content-type:
execute_code('''
import requests
resp = requests.post(url, json=payload, timeout=10)
print(f"status={resp.status_code}")
print(f"headers={dict(resp.headers)}")
ct = resp.headers.get("Content-Type", "")
if "application/json" in ct:
print(resp.json())
else:
print(f"unexpected content-type {ct!r}, body={resp.text[:500]!r}")
''')
故障原因:预期为 JSON 却收到 HTML 错误页面、空响应体、字符集错误。
第 6 步 — 语义验证
解析成功 — 但数据正确吗?
"status": "active"的含义是否与你的代码预期一致?- 响应中的 ID 是否与请求的 ID 匹配?
- 时间戳是否在预期的时区?
- 分页是否返回了所有结果,还是仅返回了第 1 页?
HTTP 状态码速查表
401 Unauthorized — 凭据缺失或无效
Authorization请求头确实存在吗?(使用curl -v确认)- 令牌是否正确且未过期?
- 身份验证方案是否正确?(
BearervsBasicvsToken) - 某些 API 使用查询参数(
?api_key=…)而非请求头。
403 Forbidden — 已认证但未授权
- 令牌是否具有所需的作用域/权限?
- 资源是否属于其他账户?
- IP 白名单是否阻止了你?
- 浏览器中的 CORS 问题?(检查
Access-Control-Allow-Origin)
404 Not Found — 资源不存在或 URL 错误
- 路径是否正确?(尾部斜杠、拼写错误、版本前缀)
- 资源 ID 是否存在?
- API 版本是否正确(
/v1/vs/v2/)? - 基础 URL 是否正确(staging vs prod)?
409 Conflict — 状态冲突
- 资源已存在(重复创建)?
ETag/If-Match过时?- 另一个进程并发修改?
422 Unprocessable Entity — JSON 有效,数据无效
错误响应体通常会指出有问题的字段。检查:
- 字段类型(字符串 vs 整数、日期格式)
- 必填 vs 选填
- 枚举值是否在允许集合内
429 Too Many Requests — 速率限制
检查 Retry-After 和 X-RateLimit-* 请求头。指数退避:
execute_code('''
import time, requests
def with_backoff(method, url, **kwargs):
for attempt in range(5):
resp = requests.request(method, url, **kwargs)
if resp.status_code != 429:
return resp
wait = int(resp.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait)
return resp
''')
5xx — 服务器端错误,通常不是你的错
- 500 — 服务器端 bug。捕获关联 ID,并向服务提供商提交工单。
- 502 — 上游服务不可用。实施退避 + 重试。
- 503 — 过载 / 维护中。检查状态页面。
- 504 — 上游超时。减少负载或增加超时时间。
对于所有 5xx 错误:使用带抖动的退避策略,若问题持续则发出警报。
分页与幂等性
分页。 验证是否获取了所有结果。查找 next_cursor、next_page、total_count。两种模式:
- 偏移量(
?limit=100&offset=200)— 简单,但如果数据发生变动可能会跳过项目。 - 游标(
?cursor=abc123)— 对于实时或大型数据集首选此方式。
幂等性。 对于非幂等操作(POST),发送 Idempotency-Key: <uuid>,以确保重试不会导致重复扣费或重复创建。对于支付和订单操作,这是强制要求的。
契约验证
在生产环境受到影响之前捕获架构漂移:
execute_code('''
import requests
def validate_user(data: dict) -> list[str]:
errors = []
required = {"id": int, "email": str, "created_at": str}
for field, expected in required.items():
if field not in data:
errors.append(f"missing field: {field}")
elif not isinstance(data[field], expected):
errors.append(f"{field}: want {expected.__name__}, got {type(data[field]).__name__}")
return errors
resp = requests.get(f"{BASE}/users/1", headers=HEADERS, timeout=10)
issues = validate_user(resp.json())
if issues:
print(f"contract violations: {issues}")
''')
在 API 升级后、集成新的第三方服务时,或在 CI 冒烟测试中运行。
关联 ID
始终捕获服务提供商的请求 ID — 这是获得厂商支持的最快途径:
execute_code('''
import requests
resp = requests.post(url, json=payload, headers=headers, timeout=10)
request_id = (
resp.headers.get("X-Request-Id")
or resp.headers.get("X-Trace-Id")
or resp.headers.get("CF-Ray") # Cloudflare
)
if resp.status_code >= 400:
print(f"failed status={resp.status_code} req_id={request_id} ts={resp.headers.get('Date')}")
''')
厂商 bug 报告模板:
Endpoint: POST /api/v1/orders
Request ID: req_abc123xyz
Timestamp: 2026-03-17T14:30:00Z
Status: 500
Expected: 201 with order object
Actual: 500 {"error":"internal server error"}
Repro: curl -X POST … (auth: <REDACTED>)
回归测试模板
将此文件放入 tests/ 目录,并通过 terminal('pytest tests/test_api_smoke.py -v') 运行:
import os, requests, pytest
BASE_URL = os.environ.get("API_BASE_URL", "https://api.example.com")
TOKEN = os.environ.get("API_TOKEN", "")
HEADERS = {"Authorization": f"Bearer {TOKEN}"}
class TestAPISmoke:
def test_health(self):
resp = requests.get(f"{BASE_URL}/health", timeout=5)
assert resp.status_code == 200
def test_list_users_returns_array(self):
resp = requests.get(f"{BASE_URL}/users", headers=HEADERS, timeout=10)
assert resp.status_code == 200
data = resp.json()
assert isinstance(data.get("data", data), list)
def test_get_user_required_fields(self):
resp = requests.get(f"{BASE_URL}/users/1", headers=HEADERS, timeout=10)
assert resp.status_code in (200, 404)
if resp.status_code == 200:
user = resp.json()
assert "id" in user and "email" in user
def test_invalid_auth_returns_401(self):
resp = requests.get(
f"{BASE_URL}/users",
headers={"Authorization": "Bearer invalid-token"},
timeout=10,
)
assert resp.status_code == 401
安全性
Token 处理
- 切勿记录完整的 token。进行脱敏处理:
Bearer <REDACTED>。 - 切勿在脚本中硬编码 token。从环境变量(
os.environ["API_TOKEN"])或~/.hermes/.env文件中读取。 - 如果 token 出现在日志、错误消息或 git 历史记录中,请立即轮换。
安全日志记录
def redact_auth(headers: dict) -> dict:
sensitive = {"authorization", "x-api-key", "cookie", "set-cookie"}
return {k: ("<REDACTED>" if k.lower() in sensitive else v) for k, v in headers.items()}
泄露检查清单
- URL 中的凭证。 查询字符串中的 API 密钥会出现在服务器日志、浏览器历史记录、Referer 头中 — 请使用请求头。
- 错误响应中的个人身份信息 (PII)。
/users/123上的404不应揭示用户是否存在(枚举攻击)。 - 生产环境中的堆栈跟踪。 500 错误不应泄露文件路径、框架版本。
- 内部主机名/IP。 错误主体中包含
10.x.x.x、internal-api.corp.local。 - Token 回显。 某些 API 会在错误详情中包含认证 token。请验证它们没有这样做。
- 详细的
Server/X-Powered-By头。 这会泄露技术栈信息。需在安全审查中注明。
Hermes 工具模式
terminal — 用于 curl, dig, openssl
terminal('curl -sI https://api.example.com')
terminal('openssl s_client -connect api.example.com:443 -servername api.example.com </dev/null 2>/dev/null | openssl x509 -noout -dates')
execute_code — 用于多步骤 Python 流程
当调试跨越 auth → fetch → paginate → validate 的流程时,使用 execute_code。变量在脚本执行期间持久存在,结果打印到 stdout,且上下文中不会出现 token 垃圾信息的风险:
execute_code('''
import os, requests
token = os.environ["API_TOKEN"]
base = "https://api.example.com"
H = {"Authorization": f"Bearer {token}"}
# 1. auth
me = requests.get(f"{base}/me", headers=H, timeout=10)
print(f"auth {me.status_code}")
# 2. paginate
all_users, cursor = [], None
while True:
params = {"cursor": cursor} if cursor else {}
r = requests.get(f"{base}/users", headers=H, params=params, timeout=10)
body = r.json()
all_users.extend(body["data"])
cursor = body.get("next_cursor")
if not cursor:
break
print(f"users={len(all_users)}")
''')
web_extract — 用于厂商 API 文档
提取正在调试的端点的规范,而不是猜测:
web_extract(urls=["https://docs.example.com/api/v1/users"])
delegate_task — 用于完整的 CRUD 测试扫描
delegate_task(
goal="Test all CRUD endpoints for /api/v1/users",
context="""
Follow the rest-graphql-debug skill (optional-skills/software-development/rest-graphql-debug).
Base URL: https://api.example.com
Auth: Bearer token from API_TOKEN env var.
For each verb (POST, GET, PATCH, DELETE):
- happy path: assert status + response schema
- error cases: 400, 404, 422
- log a repro curl for any failure (redact tokens)
Output: pass/fail per endpoint + correlation IDs for failures.
""",
toolsets=["terminal", "file"],
)
输出格式
报告发现时:
## Finding
Endpoint: POST /api/v1/users
Status: 422 Unprocessable Entity
Req ID: req_abc123xyz
## Repro
curl -X POST https://api.example.com/api/v1/users \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <REDACTED>' \
-d '{"name":"test"}'
## Root Cause
Missing required field `email`. Server validation rejects before processing.
## Fix
-d '{"name":"test","email":"test@example.com"}'
相关资源
systematic-debugging— 一旦隔离出失败的 API 层,即可对代码进行根本原因分析test-driven-development— 在发布修复程序之前编写回归测试