Flask(Python) + CRUD ( Postman) +MongoDB + Docker

lokeshvelayudham

Lokesh Velayudham - lowkeyy.eth

Posted on August 10, 2023

Flask(Python) + CRUD ( Postman) +MongoDB + Docker

An application on pyhton- flask framework, for CRUD operations test it using postman application and use monogodb to access and delete the data and dockerize the application

An appliction for CRUD operations on MongoDB using flask+python backend and build REST API, The REST API endpoints should be accessible via HTTP requests and tested using Postman.

The application should connect to a MongoDB database.
The application should provide the following REST API endpoints:

-1.GET /users - Returns a list of all users.
-2.GET /users/<id> - Returns the user with the specified ID.
-3.POST /users - Creates a new user with the specified data.
-4.PUT /users/<id> - Updates the user with the specified ID with the new data.
-5.DELETE /users/<id> - Deletes the user with the specified ID.
Enter fullscreen mode Exit fullscreen mode
Setup and installation
1. Create a virtual environment 
   1.  ```

python3 -m venv venv

Enter fullscreen mode Exit fullscreen mode
  1. source venv/bin/activate 3. create a new file in the directoty named app.py
  1. To install Flask and pyMongo using pip install
    1. pip install Flask pymongo 2. import the flask and pymongo into the app.py ```

App.py: https://github.com/lokeshvelayudham/corider_assignment

# import flask and pyMongo, bson
from bson import ObjectId
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo


app = Flask(__name__)

# Configure the Flask app to connect to your MongoDB database
app.config['MONGO_URI'] = 'mongodb://localhost:27017/corider'
mongo = PyMongo(app)

# Define the User collection
users = mongo.db.users


# GET /users - Returns a list of all users.
@app.route('/users', methods=['GET'])
def get_all_users():
    user_list = []
    for user in users.find():
        user_list.append({
            'id': str(user['_id']),
            'name': user['name'],
            'email': user['email']
        })
    return jsonify(user_list)



# GET /users/<id> - Returns the user with the specified ID.
@app.route('/users/<id>', methods=['GET'])
def get_user(id):
    user = users.find_one_or_404({'_id': ObjectId(id)})
    return jsonify({
        'id': str(user['_id']),
        'name': user['name'],
        'email': user['email']
    })


# POST /users - Creates a new user with the specified data.
@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    user_id = users.insert_one(data).inserted_id
    return jsonify({'message': 'User created successfully', 'id': str(user_id)})


# PUT /users/<id> - Updates the user with the specified ID with the new data.
@app.route('/users/<id>', methods=['PUT'])
def update_user(id):
    data = request.get_json()
    users.update_one({'_id': ObjectId(id)}, {'$set': data})
    return jsonify({'message': 'User updated successfully'})


# DELETE /users/<id> - Deletes the user with the specified ID.
@app.route('/users/<id>', methods=['DELETE'])
def delete_user(id):
    users.delete_one({'_id': ObjectId(id)})
    return jsonify({'message': 'User deleted successfully'})

Enter fullscreen mode Exit fullscreen mode
  1. Install & Setup MongoDb Databsae using homebrew

    1. install MongoDb community in the local 1. brew install mongodb-community@6.0
    2. To Start mongoDb server 1. brew services start mongodb-community@6.0
    3. After starting the server open a new terminal 1. mongo

    2.

    use Collection

    3.

    
    
  1. To insert the data into the db

    ```db.users.insert({
        "name": "John Doe",
        "email": "john@example.com",
        "password": "secretpassword"
        })```
    

To Test :

  1. Testing the Application using CRUD
    1. Test in the POSTMAN
    2. install postman desktop agent
      1. The REST API endpoints:
        1. GET /users - Returns a list of all users.
        2. GET /users/ - Returns the user with the specified ID.
        3. POST /users - Creates a new user with the specified data.
        4. PUT /users/ - Updates the user with the specified ID with the new data.
        5. DELETE /users/ - Deletes the user with the specified ID.

To dockerize :

  1. Create a file named Dockerfile

    1. requirements.txt

      Flask-PyMongo==2.3.0```
      
      3. create a yml file
      4. Build and run 
      docker-compose build
      docker-compose up
      5. push the docker into hub
      1. list the docker images -
      
      ``` docker images```
      
      2. login into docker -
      
      ```docker login```
      
      enter username and password
      3. create a image tag docker tag IMAGE NAME HUBNAME/IMAGE NAME -
      
      ```docker tag corider_assignment-app lokeshbx/corider_assignment-app```
      
      4. docker push IMAGE - docker push lokeshbx/corider_assignment-app 
      

Dockerfile

# Use the official Python image as the base image
FROM python:3.8

# Set environment variables for Flask
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0

# Set up a working directory
WORKDIR /Users/lokesh/Downloads/2022/web2/corider_assignment

# Copy requirements file and install dependencies
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code into the container
COPY . .

# Expose the port that the application runs on
EXPOSE 5000

# Run the application
CMD ["flask", "run"]

Enter fullscreen mode Exit fullscreen mode

Image description

video : https://youtu.be/SlQMuN_IvRY
Docker :https://hub.docker.com/repository/docker/lokeshbx/corider_assignment-app/general

💖 💪 🙅 🚩
lokeshvelayudham
Lokesh Velayudham - lowkeyy.eth

Posted on August 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024