How to create the flask restful API?

Flask is micro-framework of python language. Flask is very lightweight and it is easy to learn. Flask can be useful in microservices. So, let’s start the flask rest API tutorial.
First, we need to install the Flaks library using pip.
pip install flask
After installing Flask we need to create once the project directory. After creating the project directory we need to create the app.py file for our project.
import resources
from flask import Flask

def create_app():
    app = Flask('DEMO-APP')
    resources.create_api(app)
    return app


app = create_app()
app.run(host='0.0.0.0', port=9909, debug=True)
As shown above, it will create your flask app and will run on port 9909 on your localhost.
But wait where is that resources file. It is a list of all your API shown as below.
from flask_cors import CORS
from flask_restful import Api
from test_api import TestAPI


def create_api(app):
    # added cors as it was only giving pre-flight request
    CORS(app, resources={r"/*": {"origins": "*"}})
    api = Api(app, prefix='/api/')
    api.add_resource(TestAPI, "test")
So, As shown above here is all the list of our API that needs to be created I have shown the sample file you can add many more as per your requirements. Here we have to add the logic behind our test_api file.
from flask import current_app as app
from flask_restful import Resource

class TestAPI(Resource):

    def __init__(self):
        app.logger.info('In the constructor of {}'.format(self.__class__.__name__))

    def get(self):
        app.logger.info('Test API get request called')
        return True
Here I have shown sample Test API request it will return the True once it is called.
So, Now start your app.py file using the following command in your virtual environment.
python app.py
So, now your server is on at 9909 port localhost. Just call the API below it will return the True in your rest API response.
http://localhost:9909/api/test
Bingo, that’s it this is how you can start your first flask app.

No comments:

Powered by Blogger.