Forem

Manthan Ankolekar
Manthan Ankolekar

Posted on

Building a CRUD Application with Flask and MongoDB

In this blog, we will build a simple CRUD (Create, Read, Update, Delete) API using Flask and MongoDB. Unlike traditional relational databases, MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. We will use Flask-PyMongo for database interactions.

Prerequisites

Ensure you have the following installed:

  • Python 3.x
  • MongoDB
  • Flask
  • Flask-PyMongo
  • Flask-CORS

Project Setup

1. Clone the Repository

git clone https://github.com/manthanank/crud-flask-mongodb.git
cd crud-flask-mongodb
Enter fullscreen mode Exit fullscreen mode

2. Create a Virtual Environment

python -m venv venv
source venv/bin/activate  # On Windows: `venv\Scripts\activate`
Enter fullscreen mode Exit fullscreen mode

3. Install Dependencies

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

4. Configure the Environment

Copy the .env.example file to .env and update the MongoDB URI if necessary:

cp .env.example .env
Enter fullscreen mode Exit fullscreen mode

Inside .env, set the MongoDB connection string:

MONGO_URI=mongodb://localhost:27017/flaskdb
Enter fullscreen mode Exit fullscreen mode

5. Run the Application

python run.py
Enter fullscreen mode Exit fullscreen mode

The API will be available at http://127.0.0.1:5000/api/items.


Project Structure

crud-flask-mongodb/
│── app/
│   ├── __init__.py
│   ├── config.py
│   ├── database.py
│   ├── models.py
│   ├── routes.py
│── .env.example
│── requirements.txt
│── run.py
│── README.md
│── LICENSE
Enter fullscreen mode Exit fullscreen mode

Configuring the Flask Application

We define the Flask configuration in app/config.py:

import os
from dotenv import load_dotenv

load_dotenv()

class Config:
    MONGO_URI = os.getenv("MONGO_URI", "mongodb://localhost:27017/flaskdb")
Enter fullscreen mode Exit fullscreen mode

We initialize Flask and MongoDB in app/__init__.py:

from flask import Flask
from flask_cors import CORS
from app.config import Config
from app.database import mongo

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    mongo.init_app(app)
    CORS(app)

    from app.routes import api_bp
    app.register_blueprint(api_bp, url_prefix="/api")

    return app
Enter fullscreen mode Exit fullscreen mode

Defining the Model

Since MongoDB is a NoSQL database, we use dictionaries instead of SQLAlchemy models. We define a helper function in app/models.py to format MongoDB documents:

from app.database import mongo

class Item:
    @staticmethod
    def to_dict(item):
        return {
            "id": str(item["_id"]),
            "name": item["name"],
            "description": item.get("description", ""),
        }
Enter fullscreen mode Exit fullscreen mode

Creating API Routes

We define CRUD routes in app/routes.py using Flask Blueprints.

1. Create an Item

@api_bp.route("/items", methods=["POST"])
def create_item():
    data = request.json
    item = {"name": data["name"], "description": data.get("description")}
    result = mongo.db.items.insert_one(item)
    return jsonify({"id": str(result.inserted_id), **item}), 201
Enter fullscreen mode Exit fullscreen mode

2. Retrieve All Items

@api_bp.route("/items", methods=["GET"])
def get_items():
    items = mongo.db.items.find()
    return jsonify([Item.to_dict(item) for item in items])
Enter fullscreen mode Exit fullscreen mode

3. Retrieve a Single Item

@api_bp.route("/items/<string:item_id>", methods=["GET"])
def get_item(item_id):
    item = mongo.db.items.find_one({"_id": ObjectId(item_id)})
    if item:
        return jsonify(Item.to_dict(item))
    return jsonify({"error": "Item not found"}), 404
Enter fullscreen mode Exit fullscreen mode

4. Update an Item

@api_bp.route("/items/<string:item_id>", methods=["PUT"])
def update_item(item_id):
    data = request.json
    update_data = {"$set": {"name": data.get("name"), "description": data.get("description")}}
    result = mongo.db.items.update_one({"_id": ObjectId(item_id)}, update_data)

    if result.matched_count:
        updated_item = mongo.db.items.find_one({"_id": ObjectId(item_id)})
        return jsonify(Item.to_dict(updated_item))
    return jsonify({"error": "Item not found"}), 404
Enter fullscreen mode Exit fullscreen mode

5. Delete an Item

@api_bp.route("/items/<string:item_id>", methods=["DELETE"])
def delete_item(item_id):
    result = mongo.db.items.delete_one({"_id": ObjectId(item_id)})
    if result.deleted_count:
        return jsonify({"message": "Item deleted successfully"})
    return jsonify({"error": "Item not found"}), 404
Enter fullscreen mode Exit fullscreen mode

Testing the API

You can test the API using Postman or cURL.

  • Create an Item:
  curl -X POST http://127.0.0.1:5000/api/items -H "Content-Type: application/json" -d '{"name": "Laptop", "description": "Gaming laptop"}'
Enter fullscreen mode Exit fullscreen mode
  • Get All Items:
  curl -X GET http://127.0.0.1:5000/api/items
Enter fullscreen mode Exit fullscreen mode
  • Get a Specific Item:
  curl -X GET http://127.0.0.1:5000/api/items/1
Enter fullscreen mode Exit fullscreen mode
  • Update an Item:
  curl -X PUT http://127.0.0.1:5000/api/items/1 -H "Content-Type: application/json" -d '{"name": "Updated Laptop", "description": "High-performance gaming laptop"}'
Enter fullscreen mode Exit fullscreen mode
  • Delete an Item:
  curl -X DELETE http://127.0.0.1:5000/api/items/1
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this guide, we built a Flask CRUD API with MongoDB, using Flask-PyMongo for database interactions. This setup provides a solid foundation for building RESTful services in Flask with NoSQL databases.

🎉 Congratulations! You’ve built a Flask CRUD API with MongoDB. 🚀

Happy coding! 🚀

Exploring the Code

Visit the GitHub repository to explore the code in detail.


Top comments (0)