Sending Data from a Flask app to MongoDB Database
×


Sending Data from a Flask app to MongoDB Database

633

Introduction to Sending Data from a Flask App to MongoDB Database

Flask is a popular Python web framework known for its simplicity and flexibility. When combined with MongoDB, a NoSQL document-oriented database, it allows developers to build scalable web applications that store and manage data efficiently. In this article, we will explore how to send data from a Flask application to a MongoDB database.

Prerequisites

Before we start, make sure you have Python and Flask installed. You also need to have MongoDB installed and running on your machine or use a cloud-based MongoDB service. Additionally, we will use pymongo, the Python driver for MongoDB, to interact with the database.

pip install Flask pymongo

Setting Up the Flask Application

Create a new Python file, for example app.py, and import the necessary modules:

from flask import Flask, request, jsonify
from pymongo import MongoClient

app = Flask(__name__)

Connecting Flask to MongoDB

Establish a connection to your MongoDB database using MongoClient. Here, we will connect to a local MongoDB instance, but you can update the URI for cloud-based connections:

client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['users']

Creating a Route to Receive and Store Data

Define a route that accepts POST requests to receive data from the client and store it in MongoDB:

@app.route('/add_user', methods=['POST'])
def add_user():
    user_data = request.get_json()

    if not user_data or not 'name' in user_data or not 'email' in user_data:
        return jsonify({'error': 'Missing name or email'}), 400

    result = collection.insert_one({
        'name': user_data['name'],
        'email': user_data['email']
    })

    return jsonify({'message': 'User added', 'id': str(result.inserted_id)}), 201

Testing the Flask-MongoDB Integration

Run your Flask app with the command:

flask run

You can test the API endpoint using tools like Postman or curl by sending a POST request with JSON data:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice", "email": "alice@example.com"}' http://127.0.0.1:5000/add_user

Retrieving Data from MongoDB

You may also want to retrieve all users stored in the database. Here's a simple route for fetching all user records:

@app.route('/users', methods=['GET'])
def get_users():
    users = list(collection.find({}, {'_id': 0}))
    return jsonify(users)

Conclusion

Integrating Flask with MongoDB enables you to build dynamic web applications that store data flexibly and scale easily. This guide demonstrated how to send data from a Flask app to a MongoDB database and retrieve stored records. With this foundation, you can extend your app with more advanced CRUD operations and complex queries.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat