The Wayback Machine - https://web.archive.org/web/20241005050247/https://www.geeksforgeeks.org/sending-data-from-a-flask-app-to-mongodb-database/
Open In App

Sending Data from a Flask app to MongoDB Database

Last Updated : 10 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use.

MongoDB is an open-source database that stores data in JSON-like documents. It is classified as a NoSQL database because it is based on different fundamentals as compared to a SQL relational database.

Prerequisites

  • A decent understanding of Python and a machine with Python installed.
  • Understanding of basic concepts of Flask.
  • MongoDB is installed on your local machine if not you can refer to this article.

Configuring MongoDB

Till this step, you have a local machine with MongoDB installed on it now run the MongoDB compass and the following screen will appear. You can edit the settings or just click connect and MongoDB will be running on your local machine.

 

Setup a Development Environment

Let’s 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

 

We created a folder named `gfg` for the project, you can name it anything you want and cd (change directory) to go into your newly created directory then run the following command that will create a virtual environment for your project.

$ 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

We are done configuring a development environment now let us install the tools that we will be using including Flask, `pymongo` which provide the interface for Python-based apps to the MongoDB database.

$ pip install Flask pymongo

 

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

Creating a Flask App

We are done with the database setup and installing the required libraries now we will create a Flask app and connect it to the MongoDB we created and insert some user data into it. First, let’s create a Flask app as follows.

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

Python3




from flask import Flask
  
app = Flask(__name__)
  
  
@app.route('/')
def hello_world():
    return 'Hello, World!'
  
  
if __name__ == '__main__':
    app.run()


Over here we have created a starter Flask App 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.

Python3




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:

Python3




@app.route('/add_data', methods=['POST'])
def add_data():
    # Get data from request
    data = request.json
  
    # Insert data into MongoDB
    collection.insert_one(data)
  
    return 'Data added to MongoDB'


Here we created a route named `/add_data` 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.

Python3




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
  
    # Insert data into MongoDB
    collection.insert_one(data)
  
    return 'Data added to MongoDB'
  
  
if __name__ == '__main__':
    app.run()


Sending Data from Flask to MongoDB

Now let us 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.



Previous Article
Next Article

Similar Reads

Sending data from a Flask app to PostgreSQL Database
A database is used to store and maintain persistent data that can be retrieved and manipulated efficiently. we usually need a database, an organized collection of data for example in an e-commerce web app where we need to store the data about the users, orders, carts, shipping, etc. In a database, data is stored in such a way that it makes data tra
6 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around how we can send bulk customised emails to a group
3 min read
Making a Flask app using a PostgreSQL database
The Postgres database can be accessed via one of two methods in Python. Installing PgAdmin4 is the first step because it offers a user interface for interacting with databases and another for using the psycopg2 connector. In this post, we'll concentrate on a different approach that lets us alter the Postgres database: using the psycopg2 connector.
4 min read
Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
A Guide to Sending Data Using Cache in Django
In this article, we aim to comprehensively explore the functionality of sending data using cache in Django by providing a well-structured example implementation. Through this practical demonstration, we will delve into the intricacies of Django's caching system, ensuring that you gain a clear understanding of how to effectively utilize it for sendi
6 min read
How to Connect Mongodb Compass to Flask
An effective GUI tool for managing and visualizing MongoDB data is MongoDB Compass. On the other hand, a well-liked Python web framework for creating web apps is called Flask. Integrating your MongoDB data into your Flask web application may benefit from connecting MongoDB Compass to Flask. Through your Flask web application, you can quickly read,
2 min read
Flask login without database - Python
In this article, we will talk about Python-based Flask login without a database in this article. In order to use Flask login without a database in this method basically we are using a python dictionary through which users will be able to log in using their login credentials that we add to the database and also the functionality of logout will be ad
4 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide current weather updates of cities searched. Basic setu
2 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to write applications without writing the low-level codes
3 min read
Dockerize your Flask App
Python provides many ways to distribute your python projects. One such way is by using an important technology called Docker. Docker is an open-source application that allows administrators to create, manage, deploy, and replicate applications using containers. It is basically a platform that enables developers to make their applications portable b
4 min read
Flask project - Create a Joke App with PyJokes
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. For creating joke app we need two libra
2 min read
How to Run Python Flask App Online using Ngrok?
Python Flask is a popular web framework for developing web applications, APIs, etc. Running flask apps on the local machine is very simple, but when it comes to sharing the app link to other users, you need to setup the whole app on another laptop. This article provides an interesting way to setup your web app online. Then, you can send the link to
2 min read
Create a Real Time Currency Converter app using Flask | Python
Prerequisite: installation of PythonWhat is Flask in Python ? Flask is a popular and lightweight Python web framework, meaning it is a third-party Python library used for developing web applications. Project Setup : create a new directory and name it 'CURRENCY-CONVERTER'. mkdir CURRENCY-CONVERTER && cd CURRENCY-CONVERTER Inside it create tw
8 min read
How to run Flask App on Google Colab?
Flask is a web framework in python language. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a machine learning webapp. Google Colab provides a VM(virtual machine) so we canno
2 min read
Build a Text Translator Web App using Flask and Azure Cognitive Services
We're going to create a website that will translate text into multiple languages using Artificial Intelligence(AI). We'll use Flask framework for the Front end and Azure Cognitive Services(collection of AI services) for the Back end. To get started writing our Flask application with Python, we need to set up our development environment, which will
7 min read
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL ("/") is associated with the root URL. So if our site's domain was www.example.org and we want to add rout
3 min read
How to execute raw SQL in Flask-SQLAlchemy app
In this article, we are going to see how to execute raw SQL in Flask-SQLAlchemy using Python. Installing requirements Install the Flask and Flask-SQLAlchemy libraries using pip pip install Flask pip install flask_sqlalchemySyntaxTo run raw SQL queries, we first create a flask-SQLAlchemy engine object using which we can connect to the database and e
4 min read
How to Change Port in Flask app
In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we just need to provide the port while running the Flas
1 min read
How to Build a Web App using Flask and SQLite in Python
Python-based Flask is a microweb framework. Typically, a micro-framework has little to no dependencies on outside frameworks. Despite being a micro framework, practically everything may be developed when and as needed utilizing Python libraries and other dependencies. In this post, we'll develop a Flask application that collects user input in a for
4 min read
Flask - Language Detector App
In this article, we will see how we can detect the language of an entered text in Python using Flask. To detect language using Python we need to install an external library called "langdetect" and "pycountry". Let's see how to implement Flask Language Detector App, before implementation we will try to understand the basic modules that we will need
4 min read
How To Add Authentication to Your App with Flask-Login
Whether it is building a simple blog or a social media site, ensuring user sessions are working correctly can be tricky. Fortunately, Flask-Login provides a simplified way of managing users, which includes easily logging in and out users, as well as restricting certain pages to authenticated users. In this article, we will look at how we can add Au
9 min read
Deploy Python Flask App on Heroku
Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. This article revolves around how to deploy a flask app on Heroku. To demonstrate this, we are first going to create a sample application for a better understanding of the process. Prerequisites Pyt
2 min read
FastAPI - Mounting Flask App
A modern framework in Python that is used for building APIs is called FastAPI while a micro web framework written in Python that is used for developing web applications is called Flask. The FastAPI and Flask provide different features. Sometimes, it becomes crucial to use features of both in a single app. This can be possible by mounting the Flask
2 min read
Placement Prediction App using Flask
Machine learning is a widely employed method for making predictions. Numerous algorithms are accessible in different libraries for predictive tasks. In this article, we'll construct a placement prediction model using Random Forest Classifier with historical data and later we will store that model to .pkl file to integrate it with our Flask app usin
9 min read
Wikipedia search app using Flask Framework - Python
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Installation: 1) In order to create the
2 min read
Practice Tags :