loading...

create RestAPI for your python scripts using Flask with 15 line of code 😎

aaahmedaa profile image Ahmed Khaled MOhamed ・2 min read

Creating virtualenv for save working

-if you don't have virtualenv installed do it using pip install virtualenv
-execute the following :-
mkdir flask-safe-env
virtualenv .
Scripts/activate if you have any problem executing the activate script check this LINK
mkdir rest-api
cd rest-api
-install the required packages for this app by using
pip install flask
pip install flask-restful
OR if you have the github repo run pip install -r requirements.txt

Creating the project files

we can make all of the application in one script but for adding more reliability to the project we will create the sum function in a another script called sumTwoNumbers.py and import it in the app.py script to use it.

sumTwoNumbers.py

simple enough create a function that accepts two parameters and return the sum of the two numbers

def sumTwo(a, b):
    return int(a)+int(b)

app.py

we create instance of the flask app and the api module and then we add the route that accepts two params in the url using GET request we will call the function from the sumTwoNumbers script

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

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

class sumNumbers(Resource):
    def get(self, first_number, second_number):
        return {'data': sumTwoNumbers.sumTwo(first_number,second_number)}

api.add_resource(sumNumbers, '/sumtwonumbers/<first_number>/<second_number>')

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

-to run the app execute the command python app.py
-go to http://localhost:5000/sumtwonumbers/10/60 you can replace the numbers with the one you want

you can find the project files here : Sweet-github

Discussion

pic
Editor guide