使用 Python 构建一个简单的 RESTful API 服务
在现代软件开发中,构建 RESTful API 是前后端分离架构中不可或缺的一部分。Python 凭借其简洁的语法和强大的第三方库(如 Flask、FastAPI)成为实现 RESTful API 的热门选择之一。
本文将介绍如何使用 Python 的 Flask 框架来构建一个简单的 RESTful API,并演示如何进行基本的 CRUD(创建、读取、更新、删除)操作。我们将通过一个“待办事项”(To-Do List)管理系统的示例项目来展示整个过程。
环境准备
首先确保你的系统已经安装了 Python 3.x。我们还将使用 pip
来安装所需的依赖包。
pip install flask
项目结构
为了便于管理和维护代码,我们可以按照如下方式组织项目:
todo-api/│├── app.py # 主程序文件└── requirements.txt # 依赖列表
requirements.txt
内容如下:
Flask==2.3.3
编写 API 接口
打开 app.py
文件并编写以下内容:
from flask import Flask, jsonify, request, abortapp = Flask(__name__)# 模拟数据库中的数据todos = [ {"id": 1, "title": "学习 Flask", "done": False}, {"id": 2, "title": "写一篇技术文章", "done": True}]# 获取所有待办事项@app.route('/api/todos', methods=['GET'])def get_todos(): return jsonify({"todos": todos})# 获取单个待办事项@app.route('/api/todos/<int:todo_id>', methods=['GET'])def get_todo(todo_id): todo = next((t for t in todos if t['id'] == todo_id), None) if todo is None: abort(404) return jsonify(todo)# 创建新的待办事项@app.route('/api/todos', methods=['POST'])def create_todo(): if not request.json or not 'title' in request.json: abort(400) new_todo = { 'id': todos[-1]['id'] + 1 if len(todos) > 0 else 1, 'title': request.json['title'], 'done': request.json.get('done', False) } todos.append(new_todo) return jsonify(new_todo), 201# 更新待办事项@app.route('/api/todos/<int:todo_id>', methods=['PUT'])def update_todo(todo_id): todo = next((t for t in todos if t['id'] == todo_id), None) if todo is None: abort(404) if not request.json: abort(400) todo['title'] = request.json.get('title', todo['title']) todo['done'] = request.json.get('done', todo['done']) return jsonify(todo)# 删除待办事项@app.route('/api/todos/<int:todo_id>', methods=['DELETE'])def delete_todo(todo_id): global todos todos = [t for t in todos if t['id'] != todo_id] return jsonify({'result': True})# 错误处理@app.errorhandler(404)def not_found(error): return jsonify({'error': 'Not found'}), 404@app.errorhandler(400)def bad_request(error): return jsonify({'error': 'Bad request'}), 400if __name__ == '__main__': app.run(debug=True)
测试 API 接口
你可以使用 Postman 或者命令行工具 curl
来测试这些接口。
启动服务
运行以下命令启动 Flask 应用:
python app.py
默认情况下,服务会监听 http://127.0.0.1:5000/
。
获取所有待办事项
curl -X GET http://localhost:5000/api/todos
输出示例:
{ "todos": [ {"id": 1, "title": "学习 Flask", "done": false}, {"id": 2, "title": "写一篇技术文章", "done": true} ]}
创建一个新的待办事项
curl -X POST http://localhost:5000/api/todos \ -H "Content-Type: application/json" \ -d '{"title":"学习 FastAPI"}'
返回结果:
{ "id": 3, "title": "学习 FastAPI", "done": false}
更新某个待办事项
curl -X PUT http://localhost:5000/api/todos/3 \ -H "Content-Type: application/json" \ -d '{"title":"学习 FastAPI", "done":true}'
返回结果:
{ "id": 3, "title": "学习 FastAPI", "done": true}
删除某个待办事项
curl -X DELETE http://localhost:5000/api/todos/3
返回结果:
{"result": true}
使用 JSON Schema 验证请求数据(进阶)
为了增强接口的健壮性,我们可以引入 jsonschema
包来验证客户端提交的数据是否符合预期格式。
安装依赖:
pip install jsonschema
修改 create_todo()
函数如下:
from jsonschema import validate, ValidationErrorTODO_SCHEMA = { "type": "object", "properties": { "title": {"type": "string"}, "done": {"type": "boolean"} }, "required": ["title"]}@app.route('/api/todos', methods=['POST'])def create_todo(): try: validate(instance=request.json, schema=TODO_SCHEMA) except ValidationError as e: abort(400, description=str(e)) new_todo = { 'id': todos[-1]['id'] + 1 if len(todos) > 0 else 1, 'title': request.json['title'], 'done': request.json.get('done', False) } todos.append(new_todo) return jsonify(new_todo), 201
这样可以有效防止非法数据进入系统。
小结
本文介绍了如何使用 Python 和 Flask 构建一个具备基本 CRUD 功能的 RESTful API。虽然这个例子是基于内存存储实现的,但在实际生产环境中,我们可以将其替换为真正的数据库(如 SQLite、PostgreSQL、MongoDB 等),并结合 ORM 工具(如 SQLAlchemy、Peewee)来提高开发效率和数据安全性。
此外,还可以进一步扩展功能,例如添加身份认证(JWT)、分页支持、日志记录、单元测试等,以满足更复杂的业务需求。
如果你对性能有更高要求,也可以考虑使用 FastAPI,它基于 Python 类型提示构建,具有自动文档生成、异步支持等优势。