RESTful API 实践指南:从零到上手一个完整项目
现在我们从理论转向真实实践!下面一步步带你实现一个简单的 TODO 任务管理 RESTful API(经典入门项目),支持增删改查、分页、认证等生产级特性。你可以选择 Node.js (Express) 或 Python (FastAPI) 来实现——两者都是 2025 年最流行的选择。
1. 项目整体架构预览
RESTful API 的典型架构:客户端(浏览器/App) → HTTPS → API 网关 → 后端服务 → 数据库。
2. 实践步骤(通用流程)
- 准备环境
- 安装 Node.js (v20+) 或 Python (3.10+)
- 使用 SQLite 或 MongoDB 作为数据库(简单上手)
- 安装 Postman 或 Insomnia 用于测试
- 定义 API 接口(TODO 任务资源)
| 操作 | URL | 方法 | 请求体示例 | 响应状态码 |
|---|---|---|---|---|
| 获取任务列表 | /api/v1/todos | GET | ?page=1&limit=10&status=done | 200 |
| 获取单个任务 | /api/v1/todos/123 | GET | – | 200/404 |
| 创建任务 | /api/v1/todos | POST | {“title”: “学习REST”, “done”: false} | 201 |
| 更新任务 | /api/v1/todos/123 | PATCH | {“done”: true} | 200 |
| 删除任务 | /api/v1/todos/123 | DELETE | – | 204 |
- 实现代码示例
选项A:Node.js + Express(最经典)
// server.js
const express = require('express');
const app = express();
app.use(express.json());
let todos = []; // 模拟数据库
let nextId = 1;
// 获取列表(支持分页)
app.get('/api/v1/todos', (req, res) => {
const { page = 1, limit = 10 } = req.query;
const start = (page - 1) * limit;
const data = todos.slice(start, start + limit);
res.json({
data,
meta: { total: todos.length, page: +page, limit: +limit }
});
});
// 创建
app.post('/api/v1/todos', (req, res) => {
const todo = { id: nextId++, ...req.body, created_at: new Date() };
todos.push(todo);
res.status(201).json({ data: todo });
});
// 更新(PATCH)
app.patch('/api/v1/todos/:id', (req, res) => {
const todo = todos.find(t => t.id === +req.params.id);
if (!todo) return res.status(404).json({ error: { message: 'Not Found' } });
Object.assign(todo, req.body);
res.json({ data: todo });
});
// 删除
app.delete('/api/v1/todos/:id', (req, res) => {
todos = todos.filter(t => t.id !== +req.params.id);
res.status(204).send();
});
app.listen(3000, () => console.log('API 运行在 http://localhost:3000'));
选项B:Python + FastAPI(现代高效,自动生成文档)
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import uvicorn
app = FastAPI()
class Todo(BaseModel):
title: str
done: bool = False
todos = {}
next_id = 1
@app.get("/api/v1/todos")
def get_todos(page: int = 1, limit: int = 10):
start = (page - 1) * limit
items = list(todos.values())[start:start + limit]
return {"data": items, "meta": {"total": len(todos)}}
@app.post("/api/v1/todos", status_code=201)
def create_todo(todo: Todo):
global next_id
new_todo = {"id": next_id, **todo.dict()}
todos[next_id] = new_todo
next_id += 1
return {"data": new_todo}
@app.patch("/api/v1/todos/{todo_id}")
def update_todo(todo_id: int, update: Todo):
if todo_id not in todos:
raise HTTPException(404, "Not Found")
todos[todo_id].update(update.dict(exclude_unset=True))
return {"data": todos[todo_id]}
@app.delete("/api/v1/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int):
todos.pop(todo_id, None)
if __name__ == "__main__":
uvicorn.run(app, port=8000)
运行后访问 http://localhost:8000/docs 就能看到自动生成的交互文档!
4. 测试你的 API
用 Postman 发送请求是最常见的实践方式。
- 创建 Collection
- 添加环境变量(base_url)
- 写 Tests 脚本验证状态码和响应体
- 导出分享给团队
5. 生成交互式文档(强烈推荐)
用 Swagger UI / Redoc 自动生成文档,让前端开发者“自助式”查看和测试 API。
FastAPI 自带,Express 可以用 swagger-jsdoc + swagger-ui-express。
6. 生产级实践建议
- 认证:加 JWT 中间件,所有接口(除登录)都需要 Authorization: Bearer
- 校验:用 Joi (Node) 或 Pydantic (Python) 自动校验请求体
- 数据库:换成 PostgreSQL + Prisma (Node) 或 SQLAlchemy (Python)
- 部署:Docker 容器化 → Vercel / Render / AWS
- 监控:加 Winston / Loguru 日志,Sentry 错误追踪
- 版本迭代:用 /v1/ /v2/ 区分大版本变更
7. 马上开始!
- 复制上面的代码,新建文件运行
- 用 Postman 测试所有接口
- 扩展功能:加用户认证、任务标签、文件上传等
做完这个项目,你就真正掌握了 RESTful API 的全流程!如果想看完整 GitHub 示例仓库、加认证的代码、或用其他框架(Spring Boot、Gin Go)实现,告诉我,我马上给你贴出来~