Sending JSON Data to a Flask Using Requests in Python

How To Send JSON To Flask Using Requests

Imagine you are working on creating a Flask application and you need to send or post JSON data to the application. In this tutorial, we are going to learn how to send JSON data to the Flask application using requests.

But before that, we need to understand the basics of the Flask, requests libraries, and the JSON data.

To send JSON data to a Flask application using the Requests library in Python, create a client script that defines the URL and JSON data, and use requests.post() to send a POST request to the Flask application. In the Flask application, handle the incoming POST request, extract the JSON data using request.json, and return an appropriate response. You can also allow GET requests to retrieve JSON data from the Flask application by modifying the @app.route() decorator and handling the GET request accordingly.

Introduction to Flask and JSON Data

Flask is a Python web application framework that is designed to aid developers build lightweight web applications. Flask allows the development of amazing web applications with minimal code requirements.

It can be installed using the following code.

pip install flask

Let us see an example of creating a basic Hello Wprls program using Flask. Before we move on to the program, we need to understand that by default, a Flask application is run on the local host server(http://localhost:5000/).

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

In the first line, we import the flask module from the library.

Next, we create an instance for the app object in the following line. The instance is saved in the app object.

The app.route is a decorator used to declare the endpoint or the URL in which the application needs to be deployed. The URL used in this code is the default URL – http://localhost:5000/.

Next, we create a function to print the Hello,World! message on the webpage.

We are running this program using the app.run method.

Hello World Using Flask
Hello World Using Flask

Requests: HTTP for Humans

The Requests module is used to send HTTP requests using Python to retrieve the response data of an HTTP URL.

This library can be installed using the following command.

pip install requests

Please refer to this article to know more about the requests library

With the requests module, we can get requests using the get method, and post requests using the post method. We are going to see the usage of these methods in the demonstration.

Understanding JSON Data Structure

JSON(JavaScript Object Notation) stores and transfers data across the web. It resembles a dictionary in Python and is known for being lightweight and faster.

Here is an example of a JSON array.

"name_age":[
    {"name":"X", "age":20},
    {"name":"Y", "age":18"},
    {"name":"Z", "age":22}
]

Also read: How to Pretty print JSON data?

Sending JSON Data to a Flask Application

Using the requests module, we will send such JSON data to a flask application.

Creating the Client Script

First, we must create a Python file to store the JSON data. In this example, I have created a Python file called client.py, which has the JSON data.

import requests
url = 'http://localhost:5000/api/data'
json_data = {
    'Name': 'VD',
    'Job':'Dev',
}
response = requests.post(url, json=json_data)
if response.status_code == 200:
    print('JSON data sent successfully!')
else:
    print('Failed to send JSON data:', response.status_code)

Now, we import the requests module. Then, we define the URL to which the application will be deployed. Next, we define the json_data, which has two key-value pairs- Name and Job. Next, we create a requests object to post the data in the URL. For every request we send, we get a response code. In the case of 200, we have successfully sent the data to the application.

Building the Flask Application

Next, we create another file for the flask application. In this example, we use apptest.py.

from flask import Flask, request

app = Flask(__name__)

@app.route('/api/data', methods=['POST'])  
def api_data():
    if request.method == 'POST':
        data = request.json 
        print('Received JSON data:', data)
        return 'JSON data received successfully!', 200
    else:
        return 'Method Not Allowed', 405

if __name__ == '__main__':
    app.run(debug=True)

In this file, we write the code to deploy the application to the server. In the app.route decorator, we define the endpoint of the application, which is the URL. The method allowed is POST, which is used to post requests to the application. In the api_data function, we check if the method is POST, and use a few return statements to check if the data is sent to the application successfully.

After both the files are saved, we need to execute the client.py in the terminal.

Data Sent Successfully
Data Sent Successfully

And we can see the data in the terminal of the apptest.py file, indicating that the data has been sent to the application successfully.

Received JSON data
Received JSON data

Let us check if we can see the same results in the local host URL – http://localhost:5000/api/data.

Method Not Allowed
Method Not Allowed

This happens because in the apptest.py we only allow the POST method.If we allow the GET method in the app.route decorator, we can also see the JSON data on the web page.

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api/data', methods=['GET', 'POST'])  
def api_data():
    if request.method == 'POST':
        data = request.json  
        print('Received JSON data:', data)
        return 'JSON data received successfully!', 200
    elif request.method == 'GET':
           json_data = {
            'Name': 'VD',
            'Job': 'Dev',
        }
        return jsonify(json_data)

if __name__ == '__main__':
    app.run(debug=True)

In the decorator, we have added the GET method. In addition to this, we have also included an if-else statement to accommodate the requests. This allows us to get the data from the Flask application in the local host server.

Get Requests
Get Requests

We have curated a collection of interesting Flask tutorials on our platform. Please check them out!

Also read: Flask Tutorials

Summary

In this tutorial, we discussed the Flask framework basics, the requests module, and JSON data.

Following that, we used the requests module to successfully send JSON data to a flask application. The example also demonstrated how to get the response data using the two methods of the flask decorators.

This guide aims to introduce building web applications using the Flask framework. With these basics, we can do much more like deploying ML models on the web and building interesting applications. Happy Coding!

References

Flask Documentation

Requests Documentation