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
2. Create a Virtual Environment
python -m venv venv
source venv/bin/activate # On Windows: `venv\Scripts\activate`
3. Install Dependencies
pip install -r requirements.txt
4. Configure the Environment
Copy the .env.example
file to .env
and update the MongoDB URI if necessary:
cp .env.example .env
Inside .env
, set the MongoDB connection string:
MONGO_URI=mongodb://localhost:27017/flaskdb
5. Run the Application
python run.py
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
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")
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
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", ""),
}
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
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])
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
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
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
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"}'
- Get All Items:
curl -X GET http://127.0.0.1:5000/api/items
- Get a Specific Item:
curl -X GET http://127.0.0.1:5000/api/items/1
- 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"}'
- Delete an Item:
curl -X DELETE http://127.0.0.1:5000/api/items/1
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)