Flask - Calling a function with flask [duplicate]
Assume that I have the following function;
def foo(x:int):
return x*x
I need to send the input as an http request to my API (Built with flask) and get back its return value. How can I achieve this?
First thing you want to do is to create a class with a "get" method;
class Foo(Resource):
def get(self,x):
return foo(x)
After that just add it as a resource;
api.add_resource(Foo,"/foo/<int:x>")
The x here is the input of your function, make sure to add the class as the resource and not the function itself.
In the end your code should look something like the following;
from flask import Flask
from flask_restful import Resource, Api, reqparse
def foo(x:int):
return x*x
app = Flask(__name__)
api = Api(app)
task_post_args = reqparse.RequestParser()
task_post_args.add_argument('task', type=str, required=True)
class Foo(Resource):
def get(self,x):
return foo(x)
api.add_resource(Foo,"/foo/<int:x>")
if __name__ == "__main__":
app.run()