Search code examples
flaskjson-rpc

Flask class based API and jsonrpc


I just started with Flask after developing a rest API in django. I want to start using Flask and build a JSONRPC API. I'm using python 3.4 and am wondering how (and if) i can implement the API using classes, instead of the way described in the tutorials i've seen so far.

eg:

@jsonrpc.method('app.index')
def index(a):
    return 'hello {a}'.format(a=a)

Can i do something like:

class Index()
   def mymethod(self, a)
       return 'hello {a}'.format(a=a)

Can somebody point me in the right direction, if such a construct is possible at all?

The point being that i want to implement authentication for example for all my API endpoints and when using classes i could make a authentication class and use

class Index(Auth, SomeOtherBehaviour):
   def mymethod(self,a)
        return 'a'

Am i looking to it the right way (coming from Django this seems familiar) or is there another/better way how this is done in Flask?


Solution

  • It depends on the purpose of the API.

    If you are trying to allow clients to:
    - Get information about an object
    - Create and store a new object
    - Update an old object
    - Delete an existing object

    Then you are created a API (resource = object instance) based around Resources and you should be using a RESTful api such as flask-Restful. If your creating a website and are trying to organize these resources, store them in a database, display them, and interact with them through an api you should use Django because all these issues have been solved already with Django's ORM.

    if you are trying to allow clients to:
    - Remotely issue function like commands to a server based on parameters

    Then you are creating an RPC API and should use something like flask-jsonrpc.

    Good luck on your project.