Calling flask restful API resource methods

user3026153 picture user3026153 · Nov 24, 2013 · Viewed 12.5k times · Source

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...

Answer

Miguel picture Miguel · Nov 24, 2013

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.