使用 Python 模块实现 REST API
我们将使用 Python 的 Flask 框架来实现一个简单的 REST API。Flask 是一个轻量级的 Web 框架,非常适合用来快速构建 Web 应用程序和 RESTful API。
实例
from flask import Flask, jsonify, request
app = Flask(__name__)
# 示例数据
books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"},
{"id": 3, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}
]
# 获取所有书籍
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# 获取特定书籍
@app.route('/books/', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
else:
return jsonify({"error": "Book not found"}), 404
# 添加新书籍
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
# 更新书籍信息
@app.route('/books/', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
updated_data = request.get_json()
book.update(updated_data)
return jsonify(book)
else:
return jsonify({"error": "Book not found"}), 404
# 删除书籍
@app.route('/books/', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book['id'] != book_id]
return jsonify({"result": "Book deleted"})
if __name__ == '__main__':
app.run(debug=True)
app = Flask(__name__)
# 示例数据
books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"},
{"id": 3, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}
]
# 获取所有书籍
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# 获取特定书籍
@app.route('/books/', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
else:
return jsonify({"error": "Book not found"}), 404
# 添加新书籍
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
# 更新书籍信息
@app.route('/books/', methods=['PUT'])
def update_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
updated_data = request.get_json()
book.update(updated_data)
return jsonify(book)
else:
return jsonify({"error": "Book not found"}), 404
# 删除书籍
@app.route('/books/', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book['id'] != book_id]
return jsonify({"result": "Book deleted"})
if __name__ == '__main__':
app.run(debug=True)
代码解析:
- 我们首先导入了 Flask 框架和相关的模块。
- 创建了一个 Flask 应用实例
app
。 - 定义了一个示例数据
books
,它是一个包含书籍信息的列表。 - 使用
@app.route
装饰器定义了四个路由:/books
(GET): 获取所有书籍。/books/<int:book_id>
(GET): 获取特定书籍。/books
(POST): 添加新书籍。/books/<int:book_id>
(PUT): 更新书籍信息。/books/<int:book_id>
(DELETE): 删除书籍。
- 在每个路由处理函数中,我们使用
jsonify
函数将数据转换为 JSON 格式并返回。 - 最后,使用
app.run(debug=True)
启动 Flask 应用,并启用调试模式。
输出结果:
运行此代码后,Flask 应用将在本地启动,默认监听 http://127.0.0.1:5000/
。你可以使用 Postman 或 curl 等工具来测试这些 API 端点。例如:
- 获取所有书籍:
GET http://127.0.0.1:5000/books
- 获取特定书籍:
GET http://127.0.0.1:5000/books/1
- 添加新书籍:
POST http://127.0.0.1:5000/books
并在请求体中提供 JSON 数据。 - 更新书籍信息:
PUT http://127.0.0.1:5000/books/1
并在请求体中提供更新的 JSON 数据。 - 删除书籍:
DELETE http://127.0.0.1:5000/books/1
点我分享笔记