####################
# Flask: example about RESTful API

####################

from flask import Flask, jsonify, request

# Generation of a Flask instance
app = Flask(__name__)

# Sample data (can be replaced with a database)
books = [
    {"id": 1, "title": "Narcis", "author": "John Doe"},
    {"id": 2, "title": "The Glass Bead Game", "author": "Hermann Hesse"},
]

# Route to get all books
@app.route('/api/books', methods=['GET'])
def get_books():
    return jsonify(books)

# Route to get a specific book by book_id
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
    # Search for the book with the given book_id
    for book in books:
        if book['id'] == book_id:
            return jsonify(book), 200
    
    # If no book found with the given book_id, return an error message
    return jsonify({"error": "Book not found"}), 404

# Route to add a new book
@app.route('/api/books', methods=['POST'])
def add_book():
    data = request.json
    new_book = {"id": len(books) + 1, "title": data['title'], "author": data['author']}
    books.append(new_book)
    return jsonify(new_book), 201

if __name__ == '__main__':
    app.run()
