Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling flask restful API resource methods

I'm creating an API with Flask that is being used for a mobile platform, but I also want the application itself to digest the API in order to render web content. I'm wondering what the best way is to access API resource methods inside of Flask? For instance if I have the following class added as a resource:

class FooAPI(Resource):
    def __init__(self):
        # Do some things
        super(FooAPI, self).__init__()
    def post(self, id):
        #return something
    def get(self):
        #return something

api = Api(app)
api.add_resource(FooAPI, '/api/foo', endpoint = 'foo')

Then in a controller I want:

@app.route("/bar")
def bar():
   #Get return value from post() in FooAPI

How do I get the return value of post() from FooAPI? Can I do it somehow through the api variable? Or do I have to create an instance of FooAPI in the controller? It seems like there has to be an easy way to do this that I'm just not understanding...

like image 777
user3026153 Avatar asked Nov 23 '13 23:11

user3026153


People also ask

What is resource in Flask RESTful?

resource ( Type[Resource] ) – the class name of your resource. urls (str) – one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to the resource method as args. endpoint (str) – endpoint name (defaults to Resource. __name__.

Is Flask RESTful deprecated?

It seems like Flask-Restful isn't actively maintained anymore according to https://github.com/flask-restful/flask-restful/issues/883, which lists alternatives, including Marshmallow in place of reqparse.

What is the difference between Flask and Flask RESTful?

Flask Restful is an extension for Flask that adds support for building REST APIs in Python using Flask as the back-end.


1 Answers

The obvious way for your application to consume the API is to invoke it like any other client. The fact that the application would be acting as a server and a client at the same time does not matter, the client portion can place requests into localhost and the server part will get them in the same way it gets external requests. To generate HTTP requests you can use requests, or urllib2 from the standard library.

But while the above method will work just fine it seems overkill to me. In my opinion a better approach is to expose the common functionality of your application in a way that both the regular application and the API can invoke. For example, you could have a package called FooLib that implements all the shared logic, then FooAPI becomes a thin wrapper around FooLib, and both FooAPI and FooApp call FooLib to get things done.

like image 169
Miguel Avatar answered Oct 13 '22 00:10

Miguel