Search code examples
pythonflaskflask-restful

flask binding resource to an endpoint


as i know so far there are two ways of binding resouces to an endpoint using flask framework, the first one is using the @app.route decorator, like this:

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'

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

the second way is to create a class that inherite from Resources in flask-restfull, this class contains the http methods as functions, we bind it to an endpoint using add_resource method, as follow:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return 'Hello, World!'

api.add_resource(HelloWorld, '/')

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

as I understand this two different syntaxes do the same thing, what I dont understand is what is the difference between the two ? or is one designed for a specific type of applications and the other to another type of applications ?


Solution

  • Flask-RESTful is an extension of Flask, which itself is built on many of the excellent utilities provided by Werkzeug.

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/foo')
    def say_foo():
        return 'foo'
    
    @app.route('/bar')
    def say_bar():
        return 'bar'
    
    if __name__ == '__main__':
        app.run()
    

    One of the biggest ideas behind REST is using HTTP to interact with resources. The problem with this code is our resource is split up over multiple methods. There's no encapsulation. While the API itself incorporates basic elements of REST, the code completely fails to capture these ideas. This is bad! There's no reason our internal code shouldn't match the external appearance of our API.

    Using Flask-RESTful

    from flask import Flask
    from flask_restful import Resource, Api
    
    app = Flask(__name__)
    api = Api(app)
    
    class Foo(Resource):
        def get(self):
            return 'foo'
    
    class Bar(Resource)
    def get(self):
        return 'bar'
    
    # As you might have guessed, these two lines add a given resource to our API at the 
    # specified route. We no longer need to enumerate what methods a route supports, 
    # since Flask-RESTful resolves this information by inspecting what methods you've 
    # defined on your resource object.
    
    api.add_resource(Foo, '/foo')
    api.add_resource(Bar, '/bar')
    
    if __name__ == '__main__':
        app.run()
    

    We have classes now! This is a huge deal. Our routes now map directly to objects. Even better, the methods on a given class are exactly the same as their HTTP counterparts. We no longer have to deal with naming methods on our routes like say_foo, since there's a 1 to 1 mapping between HTTP methods and methods on our classes.

    read more: https://dougblack.io/words/flask-restful-101.html