首页 › Flask Web 开发 › 开发 REST API
开发 REST API
前后端分离的项目中,后端通常只提供 JSON 格式的 API。本节用 Flask 实现一个待办事项的增删改查接口。
设计接口
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | /api/todos | 获取列表 |
| POST | /api/todos | 新建 |
| GET | /api/todos/<id> | 获取单个 |
| PUT | /api/todos/<id> | 修改 |
| DELETE | /api/todos/<id> | 删除 |
实现
from flask import Flask, jsonify, request, abort
app = Flask(__name__)
todos = {1: {"id": 1, "title": "学习 Flask", "done": False}}
next_id = 2
@app.get("/api/todos")
def list_todos():
done = request.args.get("done")
items = list(todos.values())
if done is not None:
items = [t for t in items if t["done"] == (done == "true")]
return jsonify(items)
@app.post("/api/todos")
def create_todo():
global next_id
data = request.get_json(silent=True) or {}
title = (data.get("title") or "").strip()
if not title:
return {"error": "title 不能为空"}, 400
todo = {"id": next_id, "title": title, "done": False}
todos[next_id] = todo
next_id += 1
return todo, 201
@app.get("/api/todos/<int:todo_id>")
def get_todo(todo_id):
todo = todos.get(todo_id) or abort(404)
return todo
@app.put("/api/todos/<int:todo_id>")
def update_todo(todo_id):
todo = todos.get(todo_id) or abort(404)
data = request.get_json(silent=True) or {}
todo["title"] = data.get("title", todo["title"])
todo["done"] = bool(data.get("done", todo["done"]))
return todo
@app.delete("/api/todos/<int:todo_id>")
def delete_todo(todo_id):
todos.pop(todo_id, None) or abort(404)
return "", 204
@app.errorhandler(404)
def not_found(e):
return {"error": "资源不存在"}, 404
用 curl 测试
$ curl http://127.0.0.1:5000/api/todos
$ curl -X POST -H "Content-Type: application/json" \
-d '{"title": "写周报"}' http://127.0.0.1:5000/api/todos
$ curl -X PUT -H "Content-Type: application/json" \
-d '{"done": true}' http://127.0.0.1:5000/api/todos/2
$ curl -X DELETE http://127.0.0.1:5000/api/todos/2
用 Python 调用
import requests
base = "http://127.0.0.1:5000/api/todos"
r = requests.post(base, json={"title": "学习 requests"})
print(r.status_code, r.json())
print(requests.get(base).json())
设计要点
- 用 HTTP 方法表达动作,用 URL 表示资源;
- 正确使用状态码:200 成功、201 已创建、204 无内容、400 参数错误、404 不存在;
- 错误信息也返回 JSON,格式保持一致;
- 对输入做校验,不要相信客户端发来的任何数据;
- 真实项目中数据存数据库,并为接口添加认证。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 为待办 API 增加分页:GET /api/todos?page=2&size=10。
查看参考答案
@app.get("/api/todos")
def list_todos():
page = max(int(request.args.get("page", 1)), 1)
size = min(max(int(request.args.get("size", 10)), 1), 100)
items = list(todos.values())
start = (page - 1) * size
return {"total": len(items), "page": page, "items": items[start:start + size]}