Open In App

How to return a JSON response from a Flask API ?

Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask.

Prerequisites: Introduction to REST API



What is a REST API?

REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework for building web applications.



Approaches: We are going to write a simple flask API that returns a JSON response using two approaches:

  1. Using Flask jsonify object.
  2. Using the flask_restful library with Flask.

Libraries Required:

pip install Flask
pip install Flask-RESTful

Approach 1: Using Flask jsonify object – In this approach, we are going to return a JSON response using the flask jsonify method. We are not going to use the flask-restful library in this method.

app = Flask(__name__)
@app.route('/path_of_the_response', methods = ['GET'])
def ReturnJSON():
  pass
if __name__=='__main__':
    app.run(debug=True)

Code:




from flask import Flask,jsonify,request
  
app =   Flask(__name__)
  
@app.route('/returnjson', methods = ['GET'])
def ReturnJSON():
    if(request.method == 'GET'):
        data = {
            "Modules" : 15,
            "Subject" : "Data Structures and Algorithms",
        }
  
        return jsonify(data)
  
if __name__=='__main__':
    app.run(debug=True)

Output:

Approach 2: Using the flask_restful library with Flask – In this approach, we are going to create a simple JSON response with the help of the flask-restful library. The steps are discussed below:

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

Code:




from flask import Flask
from flask_restful import Api, Resource
  
app =   Flask(__name__)
  
api =   Api(app)
  
class returnjson(Resource):
    def get(self):
        data={
            "Modules": 15
            "Subject": "Data Structures and Algorithms"
        }
        return data
  
api.add_resource(returnjson,'/returnjson')
  
  
if __name__=='__main__':
    app.run(debug=True)

Output:


Article Tags :