回顾与练习
关键要点
- 是一个程序向另一个程序提供的请求菜单,也是一份契约:按约定的方式提问,就会得到约定形状的回答。大多数 API 缺陷,都是某一方破坏了这份契约。
- 是回答返回时的格式——由键和值构成,用对象
{ }和数组[ ]搭建,并且会嵌套。数据类型有 string、number、boolean、null、array、object。 - 字符串与数字的陷阱(
42对"42")以及缺失与null之分,是最常见的形状缺陷。你现在能读 JSON 了——遇到行为怪异时,去检查值的类型。 - API 密钥就是密码。绝不要发送到浏览器,绝不要提交进 ,把它存在环境变量里。泄露的密钥应当立即轮换(rotate)。
- 留意速率限制(
429)和按量计费——AI 写的、毫不停顿地调用付费 API 的循环,正是你收到四位数账单的途径。先读定价,并设置预算提醒。
动手试试
在浏览器里找一个无需密钥的免费 API——比如在新标签页直接打开 https://api.github.com/users/octocat。你会看到一段原始 JSON 响应。像读表单一样读它:挑出对象 { },如果有数组就找出来,并为三个不同的值说出它们的类型(哪些是字符串?数字?布尔值?有没有是 null 的?)。你刚刚做的,正是本章要求你对 AI 接入的每个 API 响应都做的那项检查。
本章提示词
I'm calling an API and I want to check the data shape myself, as a beginner.
Here are the real docs (example request + example response):
<paste the example request and JSON response from the API's docs>
- Before writing parsing code, show me the raw JSON the call returns and
point out the keys, their types, and anything that might be null or missing.
- Confirm the keys my code reads actually exist in that response.
- Make sure the API key is read from an environment variable on the server,
never hardcoded or sent to the browser.
- Tell me what happens if the call fails, times out, or hits a rate limit.