Sending Data from a Flask app to MongoDB Database (original) (raw)

Flask provides a lightweight framework for building web applications and APIs, while MongoDB offers a flexible NoSQL database for storing data. The project covers setting up a Flask application, connecting it to MongoDB using PyMongo, creating a POST endpoint, and inserting JSON data into a database collection.

Prerequisites

Configuring MongoDB

Open MongoDB Compass and connect to the local MongoDB server. After a successful connection, the database instance will be ready for use in the Flask application.

Setup a Development Environment

Configure the virtual environment for development, this step can be skipped but it is always recommended to use a dedicated development environment for each project to avoid dependency clash, this can be achieved using a Python virtual environment.

# Create gfg folder
$ mkdir gfg

# Move to gfg folder
$ cd gfg

A folder named gfg is created to store the project files, although any folder name can be used. Navigate to the project directory using the cd command and create a virtual environment by running the following command:

$ python -m venv venv

Now to use the virtual environment we need to first activate it, this can be done by executing the activated binary file.

$ .\venv\Scripts\activate # for Windows OS
$ source venv/bin/activate # for Linux OS

Installing Dependencies for the Project

With the development environment set up, install the required dependencies for the project. Flask is used to build the web application, while pymongo enables Python applications to interact with MongoDB databases.

$ pip install Flask pymongo

Next, connect a FLask app to MongoDB and send some data into it.

Creating a Flask App

After setting up MongoDB and installing the required libraries, create a Flask application and connect it to the MongoDB database to store user data.

Create a `main.py` file in the project directory and add the following code to the file.

Python `

from flask import Flask

app = Flask(name)

@app.route('/') def hello_world(): return 'Hello, World!'

if name == 'main': app.run(debug=True)

`

Over here a starter Flask App is created with a single route that returns a string "Hello, World!", Now test this thing out by running the app as shown below:

**Output:

The app is up and running now let us test the output at `http://127.0.0.1:5000\`,

Connecting Flask App to Database

We have got a running starter Flask App with some basic code let's connect it to the MongoDB database using the following script.

Python `

from flask import Flask, request from pymongo import MongoClient

Flask app object

app = Flask(name)

Set up MongoDB connection

client = MongoClient('mongodb://localhost:27017/') db = client['demo'] collection = db['data']

`

The above script will connect to the MongoDB database that we configured earlier now we need a post route to add some data in the database which can be done as follow:

Python `

@app.route('/add_data', methods=['POST']) def add_data(): # Get data from request data = request.json

if not data:
    return 'Invalid JSON data', 400

# Insert data into MongoDB
collection.insert_one(data)
return 'Data added to MongoDB'

`

Here a route named `/add_data` is created which when invoked with a post request reads the JSON data from the body and inserts it into the database.

For reference here is the overall code that I used for the demo.

Python `

from flask import Flask, request from pymongo import MongoClient

app = Flask(name)

root route

@app.route('/') def hello_world(): return 'Hello, World!'

Set up MongoDB connection and collection

client = MongoClient('mongodb://localhost:27017/')

Create database named demo if they don't exist already

db = client['demo']

Create collection named data if it doesn't exist already

collection = db['data']

Add data to MongoDB route

@app.route('/add_data', methods=['POST']) def add_data(): # Get data from request data = request.json

if not data:
    return 'Invalid JSON data', 400

# Insert data into MongoDB
collection.insert_one(data)

return 'Data added to MongoDB'

if name == 'main': app.run(debug=True)

`

Example JSON Payload

{
"name": "John",
"email": "john@example.com",
"city": "New York"
}

Sending Data from Flask to MongoDB

Now test the entire script and if we can insert some data into the database using it, First run the Flask App shown before then make a POST request to `/add_data` a route using a tool like Postman.

The response above looks fine let us check the MongoDB database if there is any data inserted or not.

As you can see a database named demo is created with a collection of `data` with a single document that we just inserted using Flask.