Implementing REST API with Python Modules
We will use Python's Flask framework to implement a simple REST API. Flask is a lightweight web framework that is very suitable for quickly building web applications and RESTful APIs.
Example
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
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"}
]
# Get all books
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# Get a specific book
@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
# Add a new book
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
# Update book information
@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
# Delete a book
@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__)
# Sample data
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"}
]
# Get all books
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
# Get a specific book
@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
# Add a new book
@app.route('/books', methods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
# Update book information
@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
# Delete a book
@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)
Code explanation:
- We first imported the Flask framework and related modules.
- Created a Flask application instance
app。 - Defined a sample data
books, which is a list containing book information. - Using the
@app.routedecorator, we defined four routes:/books(GET): Get all books./books/<int:book_id>(GET): Get a specific book./books(POST): Add a new book./books/<int:book_id>(PUT): Update book information./books/<int:book_id>(DELETE): Delete a book.
- In each route handler function, we use the
jsonifyfunction to convert data to JSON format and return it. - Finally, use
app.run(debug=True)to start the Flask application and enable debug mode.
Output result:
After running this code, the Flask application will start locally and listen onhttp://127.0.0.1:5000/. You can use tools like Postman or curl to test these API endpoints. For example:
- Get all books:
GET http://127.0.0.1:5000/books - Get a specific book:
GET http://127.0.0.1:5000/books/1 - Add a new book:
POST http://127.0.0.1:5000/booksand provide JSON data in the request body. - Update book information:
PUT http://127.0.0.1:5000/books/1and provide the updated JSON data in the request body. - Delete a book:
DELETE http://127.0.0.1:5000/books/1
Python3 Examples