Created On: September 20, 2024, Last Updated On: September 20, 2024

Books Flask App

Public

By Ozzie Ghani3 new


Here’s how you can design a simple RESTful API for a book management system using Flask. This API will include routes for adding, retrieving, updating, and deleting books. For simplicity, I'll store the book data in an in-memory dictionary.

Steps:

  1. Install Flask (if you don’t have it):

    bash
    pip install flask
  2. Create a basic Flask app with the following routes:

    • POST /books: Add a new book.
    • GET /books: Get all books.
    • GET /books/<id>: Get a book by its ID.
    • PUT /books/<id>: Update a book's details.
    • DELETE /books/<id>: Delete a book by its ID.

Code:

python
from flask import Flask, jsonify, request, abort app = Flask(__name__) # In-memory database (dictionary) for storing books books = {} # Helper function to generate a unique book ID def generate_id(): return max(books.keys(), default=0) + 1 # Route to add a new book @app.route('/books', methods=['POST']) def add_book(): if not request.json or 'title' not in request.json: abort(400, description="Book title is required") book_id = generate_id() new_book = { 'id': book_id, 'title': request.json['title'], 'author': request.json.get('author', "Unknown"), 'published_year': request.json.get('published_year', "N/A") } books[book_id] = new_book return jsonify(new_book), 201 # Route to get all books @app.route('/books', methods=['GET']) def get_books(): return jsonify(list(books.values())) # Route to get a specific book by ID @app.route('/books/<int:book_id>', methods=['GET']) def get_book(book_id): book = books.get(book_id) if book is None: abort(404, description="Book not found") return jsonify(book) # Route to update a book by ID @app.route('/books/<int:book_id>', methods=['PUT']) def update_book(book_id): if not request.json: abort(400, description="Bad request. JSON data is required") book = books.get(book_id) if book is None: abort(404, description="Book not found") # Update book details based on the provided fields book['title'] = request.json.get('title', book['title']) book['author'] = request.json.get('author', book['author']) book['published_year'] = request.json.get('published_year', book['published_year']) books[book_id] = book return jsonify(book) # Route to delete a book by ID @app.route('/books/<int:book_id>', methods=['DELETE']) def delete_book(book_id): book = books.pop(book_id, None) if book is None: abort(404, description="Book not found") return jsonify({'result': 'Book deleted successfully'}) # Error handler for 404 errors @app.errorhandler(404) def not_found(error): return jsonify({'error': str(error)}), 404 # Error handler for 400 errors @app.errorhandler(400) def bad_request(error): return jsonify({'error': str(error)}), 400 # Run the Flask app if __name__ == '__main__': app.run(debug=True)

Features:

  • POST /books: Add a new book by sending a JSON payload.
    • Example request payload:
      json
      { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "published_year": 1925 }
  • GET /books: Retrieve all books in the system.
  • GET /books/<id>: Retrieve a specific book by its ID.
  • PUT /books/<id>: Update the details of a book by its ID (partial updates allowed).
    • Example request payload:
      json
      { "title": "The Great Gatsby - Updated" }
  • DELETE /books/<id>: Remove a book by its ID.

Example Usage:

  • Add a book:

    bash
    curl -X POST -H "Content-Type: application/json" -d '{"title": "1984", "author": "George Orwell", "published_year": 1949}' http://127.0.0.1:5000/books
  • Get all books:

    bash
    curl http://127.0.0.1:5000/books
  • Get a book by ID:

    bash
    curl http://127.0.0.1:5000/books/1
  • Update a book by ID:

    bash
    curl -X PUT -H "Content-Type: application/json" -d '{"title": "Animal Farm"}' http://127.0.0.1:5000/books/1
  • Delete a book by ID:

    bash
    curl -X DELETE http://127.0.0.1:5000/books/1

Running the Application:

  1. Save the Python script to a file (e.g., app.py).
  2. Run the Flask app:
    bash
    python app.py
  3. Access the API on http://127.0.0.1:5000.

This is a simple implementation and doesn't persist data. In a real-world application, you could use a database (like SQLite, PostgreSQL, etc.) for storage. You could also add authentication, pagination, and better error handling for a more robust API.