Project

To create a Python API based on a MongoDB database, you can use a web framework like Flask or Django to handle HTTP requests and MongoDB drivers to interact with the database. Here, I'll provide you with a basic example using Flask and the PyMongo driver to build a simple RESTful API for your data. In our case, we use this data:

[
  { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
  { "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
  { "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 },
  { "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 },
  { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
]
  • Create a Flask App:
  • Create a Python script (e.g., "app.py") and import the necessary libraries:

    from flask import Flask, jsonify, request
    from pymongo import MongoClient
    
    app = Flask(__name__)
    
    # Connect to MongoDB
    client = MongoClient("mongodb://localhost:27017/")  # Replace with your MongoDB connection string
    db = client["your_database_name"]  # Replace with your database name
    collection = db["your_collection_name"]  # Replace with your collection name
  • Define API Endpoints:
  • Define endpoints for retrieving all books and for retrieving a book by its ID:

    @app.route('/books', methods=['GET'])
    def get_books():
        books = list(collection.find({}, {'_id': 0}))
        return jsonify(books)
    
    @app.route('/books/', methods=['GET'])
    def get_book(book_id):
        book = collection.find_one({'_id': book_id}, {'_id': 0})
        if book:
            return jsonify(book)
        else:
            return jsonify({"error": "Book not found"}), 404
  • Run the Flask App:
  • Add the following lines at the bottom of your script to run the Flask app:

    if __name__ == '__main__':
      app.run(debug=True)
  • Start the API:
  • Run your Python script ("app.py") to start the Flask web server.

    python app.py

Your API should now be running locally, and you can access it using URLs like "http://localhost:5000/books" to get all books or "http://localhost:5000/books/8752" to get a specific book by its ID.

This is a simple example to get you started. Depending on your requirements, you can expand the API to support more CRUD operations, authentication, validation, and additional features. Additionally, you can deploy the API to a production server for public access once you're satisfied with its functionality.