API
理解 APIs — 如何 applications talk 到每个 other, and 如何 REST APIs 结构请求 and 响应.
你将学到
- 什么 API 是 and 为什么它们 exist
- 如何 REST APIs use HTTP 方法 on resources
- 什么端点是 and 如何 call one
- 如何认证 protects API access
概念讲解
API
An API (Application Programming Interface) is a set of rules that lets one piece of software talk to another. Instead of a user clicking buttons, a *program* sends requests and receives data. When a weather app shows the forecast, it called a weather API to get the data.
REST APIs
REST (Representational State Transfer) is the most common API style on the web. A REST API treats everything as resources identified by URLs, and uses HTTP methods to act on them:
| Method + URL | Action | |--------------|--------| | GET /用户 | List all users | | GET /用户/42 | Get one user | | POST /用户 | Create a user | | PUT /用户/42 | Replace user 42 | | DELETE /用户/42 | Delete user 42 |
This mapping — HTTP methods onto CRUD operations (Create, Read, Update, Delete) — is the heart of REST.
Endpoints
An endpoint is a specific URL the API exposes. https://api.example.com/users is an endpoint. The combination of endpoint + method defines one operation. Documentation lists all available endpoints, their parameters, and their response shapes.
Calling an API
const response = await fetch("https://api.example.com/users/42", {
headers: { "授权": "Bearer my-令牌" }
});
const user = await response.json();
Authentication
Most APIs require authentication — proof you are allowed to access them. Common methods:
- API keys — a secret string sent in a header or query param.
- Bearer tokens / JWTs — a signed token proving your identity and permissions.
- OAuth — a protocol that lets a user grant a third party access without sharing their password.
Without authentication, anyone could read or modify any user's data. Understanding how to authenticate is essential for working with real APIs.
示例代码
// Calling a REST API to list and create users
const API_BASE = "https://api.example.com";
const token = "your-api-token";
// GET: list users
async function listUsers() {
const res = await fetch(`${API_BASE}/users`, {
headers: { "Authorization": `Bearer ${token}` }
});
return res.json();
}
// POST: create a new user
async function createUser(name, email) {
const res = await fetch(`${API_BASE}/users`, {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ name, email })
});
if (!res.ok) throw new Error(`Failed: ${res.status}`);
return res.json();
}
两者都 calls use 授权请求头使用 bearer 令牌. GET 有否 请求体; POST 发送 JSON. 检查 res.好的 ensures 我们 throw on 失败相反的 silently returning 错误对象.
动手试一试
- JWT Decoder
APIs 经常 use JWTs for 认证. Decode one 到 see claims (用户 ID, expiry, roles).
- JSON Schema Validator
APIs 定义响应 shapes 使用 JSON Schema. 验证响应针对 one.
常见错误
错误写法
Hardcoding API 键 in 客户端-边 code.
正确做法
客户端-边 code 是可见到 每个人. Keep API 键 on 服务器 or 后面 proxy. 如果你 必须包含键 客户端-边, use one 使用 restricted permissions and 速率限制.
错误写法
Assuming 获取() throws on 404 or 500.
正确做法
获取仅 拒绝 on network 失败. HTTP 错误 (4xx, 5xx) still resolve — 你必须检查响应.好的 or 响应.状态 and throw manually.
相关资源
相关指南
- JWT Security 指南
如何 use JWTs for API 认证 safely.
练习 API
5 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。