How to use Flask ‘jsonify’ object In Python
- Create a new python file named ‘main.py’.
- import Flask, jsonify and request from the flask framework.
- Register the web app into an app variable using the following syntax.
Python3
app = Flask(__name__) |
- Create a new function named ‘helloworld’. This function is going to return the ‘Hello World’ text in JSON format.
- Route the ‘helloworld’ function to your desired URL using the following syntax.
Python3
@app .route( '/path_of_the_response' , methods = [ 'GET' ]) def helloworld(): pass |
- Inside the ‘helloworld’ function if request method is ‘GET’ then create a python dictionary with the ‘Hello World’ message.
- Jsonify the python dictionary and return it.
- Build the flask application using the following command.
Python3
if __name__ = = '__main__' : app.run(debug = True ) |
- Run the ‘main.py’ file in the terminal or the IDE and type the following URL in the browser.
http://127.0.0.1:5000/hello
Code :
Python3
from flask import Flask, jsonify, request app = Flask(__name__) @app .route( '/hello' , methods = [ 'GET' ]) def helloworld(): if (request.method = = 'GET' ): data = { "data" : "Hello World" } return jsonify(data) if __name__ = = '__main__' : app.run(debug = True ) |
Output :
How to write a simple Flask API for hello world?
Prerequisites: Introduction to REST API
REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple REST API that returns ‘Hello World’, with the help of a flask.
In this article we are going to write a simple flask API for hello world using two methods:
- Using Flask jsonify object.
- Using the flask_restful library with Flask.
Contact Us