Implementing REST API with Python Modules

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. We first imported the Flask framework and related modules.
  2. Created a Flask application instanceapp。
  3. Defined a sample databooks, which is a list containing book information.
  4. 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.
  5. In each route handler function, we use thejsonifyfunction to convert data to JSON format and return it.
  6. Finally, useapp.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

Document 对象参考手册Python3 Examples

Other Extensions