Web知识篇
什么是API接口
程序之间的"翻译官"
API(Application Programming Interface,应用程序编程接口) 是不同软件之间沟通的桥梁。你不需要知道对方内部怎么实现的,只要按照约定的格式发请求,就能得到想要的数据。
💡 类比:API 就像餐厅的菜单。你不需要知道厨房怎么做菜(内部实现),只要照着菜单点菜(调用接口),就能拿到你要的菜(数据)。
加载图表中...
API 的种类
加载图表中...
在 Web 开发中,我们说的 API 通常指 Web API——通过 HTTP 请求来调用的接口。
一个 API 接口长什么样?
加载图表中...
真实案例:文章管理API
| 操作 | 方法 | 地址 | 说明 |
|---|---|---|---|
| 获取文章列表 | GET | /api/articles | 返回所有文章 |
| 获取单篇文章 | GET | /api/articles/123 | 返回id=123的文章 |
| 创建文章 | POST | /api/articles | 提交新文章数据 |
| 修改文章 | PUT | /api/articles/123 | 更新id=123的文章 |
| 删除文章 | DELETE | /api/articles/123 | 删除id=123的文章 |
调用 API 的完整流程
加载图表中...
用 JavaScript 调用 API
获取数据(GET)
// 获取文章列表
const response = await fetch("/api/articles?page=1&limit=10");
const data = await response.json();
console.log(data);
// { articles: [...], total: 100 }
创建数据(POST)
// 创建新文章
const response = await fetch("/api/articles", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer your-token",
},
body: JSON.stringify({
title: "我的新文章",
content: "文章内容...",
}),
});
const result = await response.json();
console.log(result); // { id: 456, message: "创建成功" }
完整的增删改查
// 📖 读取(Read)
const articles = await fetch("/api/articles").then(r => r.json());
// ✏️ 创建(Create)
await fetch("/api/articles", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "新文章" }),
});
// 🔄 更新(Update)
await fetch("/api/articles/123", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "修改后的标题" }),
});
// 🗑️ 删除(Delete)
await fetch("/api/articles/123", {
method: "DELETE",
});
API 的请求和响应格式
请求格式
POST /api/articles HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer sk-abc123
{
"title": "我的文章",
"content": "内容..."
}
响应格式
大多数 API 都遵循类似的响应结构:
{
"code": 200,
"message": "success",
"data": {
"id": 1,
"title": "我的文章",
"createdAt": "2024-01-01T00:00:00Z"
}
}
错误响应
{
"code": 401,
"message": "Unauthorized",
"error": "Invalid or expired token"
}
第三方 API 示例
调用天气API
const response = await fetch(
"https://api.weather.com/v1/current?city=beijing&key=your-api-key"
);
const weather = await response.json();
console.log(weather.temperature); // 25
console.log(weather.description); // "晴天"
调用 AI API(如 OpenAI)
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer sk-your-api-key",
},
body: JSON.stringify({
model: "gpt-4",
messages: [{ role: "user", content: "你好!" }],
}),
});
const result = await response.json();
console.log(result.choices[0].message.content);
Next.js 中的 API 路由
在 Next.js 中,你可以很方便地创建自己的 API:
app/
api/
articles/
route.ts → /api/articles
[id]/
route.ts → /api/articles/:id
// app/api/articles/route.ts
export async function GET() {
// 查询数据库获取文章
const articles = [
{ id: 1, title: "Hello World" },
{ id: 2, title: "Learning API" },
];
return Response.json({ articles });
}
export async function POST(request: Request) {
const body = await request.json();
// 保存到数据库...
return Response.json({ message: "创建成功", id: 123 });
}
加载图表中...
API 文档怎么看?
好的 API 都有文档,告诉你怎么调用。文档通常包含:
| 内容 | 说明 | 例子 |
|---|---|---|
| 接口地址 | URL | GET /api/articles |
| 请求参数 | 需要传什么 | page: number, limit: number |
| 请求头 | 认证信息等 | Authorization: Bearer token |
| 响应示例 | 返回什么数据 | {"articles": [...]} |
| 错误码 | 可能的错误 | 401: 未授权, 404: 未找到 |
🎯 AI编程小贴士:拿到一个 API 文档不知道怎么调用?把文档截图或文本发给 AI,告诉它你想实现什么功能,它会帮你生成完整的调用代码。
小结
- API 是程序之间沟通的标准接口
- Web API 通过 HTTP 请求调用,返回 JSON 数据
- 用
fetch()发送请求,用.json()解析响应 - RESTful API 用 方法 + 路径 表达增删改查
- Next.js 的 API Routes 可以快速创建自己的 API
- 第三方 API(天气、AI等)通常需要 API Key 认证