RESTful API 调试

用 curl 复现请求、读状态码与响应头、定位常见问题的顺序。

Beginner
Key Points调试接口先看状态码,再看响应头(Content-Type、Location、Retry-After),最后才看 body。

curl 基本用法

Bash
# GET,带认证头
curl -s -H "Authorization: Bearer $TOKEN" https://api.example.com/users/42

# POST JSON
curl -s -X POST https://api.example.com/users \
     -H "Content-Type: application/json" \
     -d '{"name":"Alice","email":"alice@example.com"}'

# PATCH 局部更新
curl -s -X PATCH https://api.example.com/users/42 \
     -H "Content-Type: application/json" -d '{"age":31}'

# DELETE
curl -s -i -X DELETE https://api.example.com/users/42

看状态码与响应头

-i prints response headers, -v also shows request headers, and -o /dev/null -w '%{http_code}' gives you just the status. For 401/403/404 that is usually enough.

Bash
curl -s -o /dev/null -w "%{http_code}\n" https://api.example.com/users/42
curl -s -i https://api.example.com/users/42 | head -12

常用工具

  • curl — 可复制、可进脚本、可贴进 issue
  • httpie — http GET url 语法更短,输出带颜色
  • Postman / Insomnia — 存集合、跑环境变量、做回归
  • Swagger UI — 文档即调试台,适合给外部对接方

排查顺序

  1. 状态码是什么 —— 4xx 是我发错了,5xx 是对方炸了
  2. Content-Type 对不对 —— 发 JSON 却写 text/plain 会被 415 拒
  3. 认证头在不在 —— 401 先看 Authorization 有没有被代理剥掉
  4. URL 有没有多余斜杠、编码是否正确 —— 空格要 %20
  5. body 里的 error.code 说了什么 —— 业务错误看这里
  6. 用 -v 对比请求头 —— 多一个 Expect: 100-continue 都可能被网关拒
Paste the minimal reproducing curl into the ticket instead of a screenshot: the other side can run it and see exactly what you sent.

Friends & Partners