passing arguments to API created by flask in python

mjoudy picture mjoudy · May 25, 2018 · Viewed 8.6k times · Source

I am a complete newbie to API and python. actually, after getting disappointed to find a free host supporting plumber in R I decided to try it by python. The simple problem is that I have a simple function which takes two numeric arguments and using a given CSV file do some calculations and returns a number (I have simply made this in R by the plumber in localhost). now for a test in python have written below code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "hello world!"

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

well, this correctly works. but when I try to make a function to take arguments like this:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello(a):
    return a + 2

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

I get this page which says I have not passed the arguments.

enter image description here

my main question is that how I can pass the arguments? (in API created by R plumber, for example, I call it like: localhost/5000/?a=2 )

my another question is, could be this kind of API host and request in something like Heroku?

Answer

rakyi picture rakyi · May 25, 2018

From Flask documentation:

You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.

So in your case that would be:

@app.route("/<int:a>")
def hello(a):
    return a + 2

Other option would be to use request data.