Open In App

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:

Installation

1. Install the python Flask library using the following command.



pip install Flask

2. Install the flask-restful library using the following command.

pip install Flask-RESTful

Method 1: Using Flask ‘jsonify’ object




app =   Flask(__name__)




@app.route('/path_of_the_response', methods=['GET'])
def helloworld():
    pass




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

http://127.0.0.1:5000/hello

Code :




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 :

Method 2: Using the flask_restful library 




app =   Flask(__name__)




api =   Api(app)




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

http://127.0.0.1:5000/hello

Code :




from flask import Flask
from flask_restful import Api, Resource
  
app =   Flask(__name__)
  
api =   Api(app)
  
class HelloWorld(Resource):
    def get(self):
        data={"data":"Hello World"}
        return data
  
api.add_resource(HelloWorld,'/hello')
  
  
if __name__=='__main__':
    app.run(debug=True)

Output :


Article Tags :