Hello World Example Demonstrating Python, Flask and REST API



Installation:

Use the following pip command to do setup in terminal / Windows command prompt:
pip install flask, flask-restful

Python Script “MyRESTAPIUsingPythonScript”:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Tracks(Resource):
    def get(self):
        result = "Hello World"
        return result

api.add_resource(Tracks, '/tracks') # URL Route

if __name__ == '__main__':
     app.run(port='5002')

Way to execute Python Script:

(base) C:\Users\ashish.jain\Desktop>python MyRESTAPIUsingPythonScript.py
 * Serving Flask app "MyRESTAPIUsingPythonScript" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5002/ (Press CTRL+C to quit)

URL to hit:


Output:

No comments:

Post a Comment