Certainly! Let's break down the development of a Flask application with CRUD operations for MongoDB into detailed steps, providing the necessary files and configurations. The application will be Dockerized for easy setup and testing.
Step-by-Step Guide
1. Directory Structure
We'll create a project with the following directory structure:
flask_mongo_app/
│
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ └── config.py
│
├── tests/
│ ├── __init__.py
│ └── test_routes.py
│
├── Dockerfile
├── requirements.txt
├── docker-compose.yml
└── README.md
2. Application Files
__init__.py: Initialize the Flask application and MongoDB connection.
# app/__init__.py
from flask import Flask
from flask_pymongo import PyMongo
mongo = PyMongo()
def create_app():
app = Flask(__name__)
app.config['MONGO_URI'] = 'mongodb://mongo:27017/user_db'
mongo.init_app(app)
from .routes import user_bp
app.register_blueprint(user_bp, url_prefix='/api')
return app
models.py: Define the user serialization function.
# app/models.py
from bson.objectid import ObjectId
def user_serializer(user) -> dict:
return {
"id": str(user["_id"]),
"name": user["name"],
"email": user["email"],
"password": user["password"]
}
routes.py: Define the REST API endpoints for CRUD operations.
# app/routes.py
from flask import Blueprint, request, jsonify
from bson.objectid import ObjectId
from . import mongo
from .models import user_serializer
user_bp = Blueprint('user_bp', __name__)
@user_bp.route('/users', methods=['GET'])
def get_users():
users = mongo.db.users.find()
return jsonify([user_serializer(user) for user in users]), 200
@user_bp.route('/users/<id>', methods=['GET'])
def get_user(id):
user = mongo.db.users.find_one({"_id": ObjectId(id)})
return jsonify(user_serializer(user)) if user else ('', 404)
@user_bp.route('/users', methods=['POST'])
def add_user():
data = request.json
new_user = {
"name": data['name'],
"email": data['email'],
"password": data['password']
}
user_id = mongo.db.users.insert_one(new_user).inserted_id
user = mongo.db.users.find_one({"_id": user_id})
return jsonify(user_serializer(user)), 201
@user_bp.route('/users/<id>', methods=['PUT'])
def update_user(id):
data = request.json
mongo.db.users.update_one(
{"_id": ObjectId(id)},
{"$set": {"name": data.get('name'), "email": data.get('email'), "password": data.get('password')}}
)
user = mongo.db.users.find_one({"_id": ObjectId(id)})
return jsonify(user_serializer(user)) if user else ('', 404)
@user_bp.route('/users/<id>', methods=['DELETE'])
def delete_user(id):
result = mongo.db.users.delete_one({"_id": ObjectId(id)})
return ('', 204) if result.deleted_count == 1 else ('', 404)
3. Docker Setup
Dockerfile: Define the Docker image.
# Dockerfile
FROM python:3.9
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run", "--host=0.0.0.0"]
docker-compose.yml: Define services for Flask app and MongoDB.
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "5000:5000"
environment:
FLASK_APP: app
FLASK_ENV: development
volumes:
- .:/app
depends_on:
- mongo
mongo:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
volumes:
mongo-data:
4. Requirements File
requirements.txt: List dependencies to be installed.
Flask==2.1.3
Flask-PyMongo==2.3.0
pymongo==3.12.1
5. Testing with Postman
- Setup Postman: Create HTTP requests to test each CRUD operation defined in
routes.py.
- Endpoints to Test:
GET /api/users: Retrieve all users.
GET /api/users/<id>: Retrieve a specific user by ID.
POST /api/users: Create a new user.
PUT /api/users/<id>: Update an existing user.
DELETE /api/users/<id>: Delete a user.
6. README File
README.md: Document setup and usage instructions.
# Flask MongoDB CRUD Application
## Description
This application is a simple Flask API that performs CRUD operations on a MongoDB database for a User resource.
## Setup
1. **Clone the repository:**
git clone
2. **Navigate to the directory:**
cd flask_mongo_app
3. **Build and run the application using Docker Compose:**
docker-compose up --build
4. **Access the application:**
- The API will be available at `http://localhost:5000/api`.
## API Endpoints
- `GET /api/users`: Retrieve a list of all users.
- `GET /api/users/<id>`: Retrieve a user by ID.
- `POST /api/users`: Create a new user.
- `PUT /api/users/<id>`: Update a user.
- `DELETE /api/users/<id>`: Delete a user.
## Testing
Use Postman to test the API endpoints listed above.
Final Steps
- Ensure you have Docker and Docker Compose installed.
- Follow the README instructions to build and run your application.
- Verify the API using Postman by testing the various endpoints.
- Push your code to GitHub and share the link for submission.
Once you've completed these steps, you'll have a well-structured, Dockerized Flask application capable of handling CRUD operations with MongoDB.