How to send JSON data in python flask

Flask is a well-known web application micro-framework written in Python using which developers can create web applications easily and efficiently. It provides a flexible, lightweight, and simple structure for creating the REST API. REST (Representational State Transfer) API is used to set guidelines for a web application to send and receive information. It can be used to exchange information between the client and server

This article will provide a step-by-step guide on how to Send JSON Data in Python Flask, demonstrating how to create a simple REST API that returns a JSON object using Flask. This makes it an ideal resource for developers who want to learn about REST API development.

Install Required Modules:

First, let’s download the required Python libraries:

  • Run this command to install Flask Library:
pip install Flask
  • Run this command to install Flask-RESTful Library:
pip install Flask-RESTful

Return a JSON Response

There are different ways to return a JSON response from a Flask API. Some of them are discussed below:

  1. Using jsonify Method
  2. Using flask_restful Library 

Using jsonify Method

To send JSON data in python using flask:

  • Use the jsonify method available in the FLASK library. This method is used to return JSON output in a Response object. Let’s see the below example that shows how to send JSON data in python flask:
#Load libraries
from flask import Flask,request,jsonify

# A Flask app instance
app = Flask(__name__)

# route the app to the given URL
@app.route('/api/example' , methods = ['GET'])


# Define app
def example_api():
if(request.method == 'GET'):
data={
"Name": "Hi! Burhan",
"Age" : 25,
"Message": "Congratulations! You have successfully return a JSON response from a Flask API",
}
return jsonify(data)

# build the Flask app
if __name__ == '__main__':
  app.run()    

Save the above code as myApp.py and run it on the command prompt or any python IDE using the following command :

python myApp.py

You can also use the below command on the command prompt to run the myApp.py file

flask --app myApp run

Output

This code is a simple Flask application that returns a JSON response when a GET request is made to the endpoint /api/example. Here’s a step-by-step explanation:

  • At first, the jsonify and all required methods are imported from the flask framework.
  • A Flask app instance is created using the Flask constructor.
  • The app is then routed to the endpoint /api/example using the @app.route method.
  • Then example_api function is created. The get method is implemented in the example_api to handle a GET request to the endpoint. In the function, a dictionary is created with some data and the jsonify method is used to convert it to a JSON response, which is returned to the client. 
  • Finally, the Flask app is run in the if __name__ == ‘__main__’ block, making it ready to receive and respond to requests.

Using flask_restful Library 

To send JSON data in python using flask:

  • Flask-RESTful library can also be used. Flask-RESTful is an extension for Flask that adds support for building REST APIs. Consider the below example of using Flask-RESTful to return a JSON response from a Flask API:
from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)

api = Api(app)

class ExampleAPI(Resource):
def get(self):
data={

"Name": "Hi! Burhan",
"Age" : 25,
"Message": "Congratulations! You have successfully return a JSON response from a Flask API",
}
return data

api.add_resource(ExampleAPI,'/api/example2')


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

Save the above code as myApp2.py and run it on the command prompt or any python IDE using the following command :

python myApp2.py
# flask --app myApp2 run

Output

The above example demonstrates how to send JSON data in python Flask using flask_restful Library. An explanation of the above code is given below:

  • Load the jsonify method from the flask framework and Api and Resource methods are imported from flask_restful library.
  • A Flask app instance is then created using the Flask constructor.
  • An instance of the Flask-RESTful Api class is created, passing the Flask app instance as an argument.
  • The Resource class named ExampleAPI is defined, which handled the endpoint for the API.
  • The get method is implemented in the ExampleAPI class to handle a GET request. This method returned a dictionary that was converted to a JSON response.
  • The add_resource method is called on the Flask-RESTful API instance, passing the ExampleAPI class and the response path /api/example2 as arguments.
  • Then if __name__ == ‘__main__’ block is used to run the Flask app in debug mode, which allows for easy debugging during development.

When a GET request is made to the /api/example2 endpoint, the get method in the ExampleAPI class is called, which returns a dictionary representing the JSON response. Flask-RESTful automatically converts this dictionary to a JSON response and sends it back to the client.

Conclusion:

A REST API, or Representational State Transfer API, defines a set of rules and constraints for designing and building web applications that communicate and exchange data over the internet. In simple terms, a REST API acts as a bridge between different components of an application and enables them to send and receive data in a structured manner.

In the context of this article, we specifically showed how to create a REST API that returns a simple JSON object in Python using the Flask framework. We utilized the jsonify method and the flask_restful library to achieve this. By leveraging these tools, we demonstrated how to send JSON data in Python flask in a clear and organized format, making it easier for different parts of the application to communicate and exchange information.

Check here for more python articles

Good Luck with your Learning !!

Related Topics:

What does pass do in Python?

How to Save Dictionary as JSON Python

Difference between fetchone and fetchall in Python

Jerry Richard R
Follow me