Skip to content

Getting Started with Flask

Rajesh Khadka edited this page Nov 18, 2019 · 2 revisions
  1. Install flask in a virtual environment
pip install flask
  1. Install Flask-RestFul
pip install flask-restful
  1. Write the first program in Flask as
from flask import Flask

app = Flask(__name__)

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

Now you can run your first applications in flask on localhost at port 5000 :

http://127.0.0.1:5000/ 
  1. Wait you have a few more things to do: Import Api and Resources from flask_restful as:
from flask_restful import Api, Resource
  1. Initialize the API with the application as:
api = Api(app, prefix='/v1')
  1. Create the first resource class to create the first endpoint:
class HelloWorldResource(Resource):
    @classmethod
    def get(cls):
        return 'Congratulations you have successfully built the first API in the flask'
  1. add resources on API as:
api.add_resource(HelloWorldResource, '')

Finally, Run the application you will get your API on the following URL:

http://127.0.0.1:5000/v1

Our final code will be:

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app, prefix='/v1')


class HelloWorldResource(Resource):
    @classmethod
    def get(cls):
        return 'Congratulations you have successfully built first api in flask'


api.add_resource(HelloWorldResource, '')

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

Github