Table of contents
1.
Introduction
2.
APIs And Rest APIs
3.
Creating A JSON Response Flask API
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

JSON Response Flask API

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Flask is one of the most popular microframeworks of Python for creating Web Applications.

Flask’s framework is more explicit than other Python frameworks and easier to learn because it has significantly less base code to implement a simple Web-Application.

Flask is based on the Werkzeug WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.

Let’s get an overview of APIs and Restful APIs.

APIs And Rest APIs

API: API stands for Application Programming Interface. An API is a contract between an information provider and an information user that establishes the content needed by the consumer and the content required by the producer.

REST API: REST stands for Representational State Transfer. A RESTFUL API or REST API allows for interaction with RESTFUL web services by conforming to the constraints of REST architectural style. It specifies rules for a web application to send and receive data.

REST API services let you interact with the database by simply making HTTP requests.

That’s how the backend of web apps is created. The data is returned in JSON format, and requests used are GETPOSTPUT and DELETE.

The following section will create a simple JSON response REST API using Flask.

Note: Before creating the API, make sure you have Flask installed in your system.

Creating A JSON Response Flask API

There are two different methods through which we can create JSON response web API:-

1.) Using Flask jsonify object.

2.) Using the flask_restful library with Flask.

Method1: Using Flask jsonify object:-

This method returns a JSON response using the flask jsonify method.

The steps are discussed below:-

Step1: Create a new python file app.py.

Step2: In this file, Import Flask, jsonify, and request from the flask framework.

from flask import Flask,jsonify,request
You can also try this code with Online Python Compiler
Run Code

 

Step3: Register your application into an app variable using the following syntax.

app = Flask(__name__)
You can also try this code with Online Python Compiler
Run Code

 

Step4: Create a new function named JSONResponse. This function will return a JSON response.

Step5: In the JSONResponse function, if the request method is GET, then create a python dictionary. Then jsonify the python dictionary(name here) and return it.

def JSONResponse():
if(request.method == 'GET'):
name = {
"fname" : "Coding",
"lname" : "Ninjas",
}
return jsonify(name)
You can also try this code with Online Python Compiler
Run Code

 

Step6: Build the Flask app using the following command.

if __name__=='__main__':
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Step7: Finally, run the app.py  file in the terminal.

The final code will look like the following:-

from flask import Flask,jsonify,request

app = Flask(__name__)

@app.route('/jsonresponse', methods = ['GET'])
def JSONResponse():
if(request.method == 'GET'):
name = {
"fname" : "Coding",
"lname" : "Ninjas",
}

return jsonify(name)

if __name__=='__main__':
app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Output: 

We will see our application is by default running on port 5000.

Go to the browser and type the URL: localhost:5000/jsonresponse. You will get the following output as JSON response.


Method2: Using the flask_restful library with Flask:-

In this method, we will create a simple JSON response with the help of the flask-restful library.

The steps are discussed below:-

Step1: Install the flask-restful library using the following command:

pip install Flask-RESTful
You can also try this code with Online Python Compiler
Run Code

 

Step2: Create a new python file app.py.

Step3: In the app.py file, Import Flask from the flask framework.

from flask import Flask
You can also try this code with Online Python Compiler
Run Code

 

Step4: In the app.py file, Import Api and Resource from the flask_restful library.

from flask_restful import Api, Resource
You can also try this code with Online Python Compiler
Run Code

 

Step5: Register your application into an app variable using the following syntax.

app = Flask(__name__)
You can also try this code with Online Python Compiler
Run Code

 

Step6: Register the app variable as an API object using the API method of the flask_restful  library.

api = Api(app)
You can also try this code with Online Python Compiler
Run Code

 

Step7: Create a resource class named JSONResponse.

Step8: Inside the resource, the class creates a get method and returns a dictionary with the simple JSON response from the get method.

class JSONResponse(Resource):
def get(self):
name = {
"fname" : "Coding",
"lname" : "Ninjas",
}
return name
You can also try this code with Online Python Compiler
Run Code

 

Step9: Add the resource class to the API using the add_resource method.

api.add_resource(JSONResponse,'/jsonresponse')
You can also try this code with Online Python Compiler
Run Code

 

Step10: Build the flask application using the following command.

if __name__=='__main__':
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Step11: Finally, run the app.py file in the terminal.

The final code will look like the following:-

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)

api = Api(app)

class JSONResponse(Resource):
def get(self):
name = {
"fname" : "Coding",
"lname" : "Ninjas",
}
return name

api.add_resource(JSONResponse,'/jsonresponse')

if __name__=='__main__':
app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Output: 

We will see our application is by default running on port 5000.

Go to the browser and type the URL: localhost:5000/jsonresponse. You will get the following output as JSON response.

Also Read About, PHP For Loop

Frequently Asked Questions

  1. What is an API?
    API stands for Application Programming Interface. An API is a contract between an information provider and an information user that establishes the content needed by the consumer and the content required by the producer.
     
  2. How to install Flask-Restful library?
    You can install the Flask-Restful library using the following command:-
pip install Flask-RESTful
You can also try this code with Online Python Compiler
Run Code

 

3. List the different methods to create a REST API with JSON response in Flask.

    There are two different methods to create JSON response web API in Flask:-

  • Using Flask jsonify object.
  • Using the flask_restful library with Flask.

Key Takeaways

In this blog, we have learned how to create a JSON response REST API using Flask, different methods to make those APIs, and a few code examples.

If you want to read more blogs related to Flask, you can visit Flask Introduction And Overview and Flask Environment and First Application. If you want to learn advanced web development blogs, you can visit Coding Ninjas Web Blogs.

Happy Learning!!

Live masterclass