52

I'm about to develop a REST API for our upcoming application. I have decided to use Python Flask for it. But at this point, I don't know which option to use. Should I be using the basic Flask package or Flask with Flask-RESTful extension. I've found some advantages and disadvantages in both.

Below is an example of two APIs doing the same thing but in Flask and Flask-RESTful:

Flask version:

from flask import Flask, jsonify

app = Flask(__name__)

usersList = ['Aaron', 'Bianca', 'Cat', 'Danny', 'Elena']

@app.route('/users', methods=['GET'])
def users():
    return jsonify({ 'users': [user for user in usersList] })

@app.route('/user/<int:id>', methods=['GET'])
def userById(id):
    return jsonify({ 'username': usersList[id]  })

@app.route('/user/<string:name>', methods=['GET'])
def getUserByName(name):
    # Show some user information
    return "Some info"

@app.route('/user/<string:name>', methods=['POST'])
def addUserByName(name):
    usersList.append(name)
    return jsonify({ 'message': 'New user added'  })

app.run()

Flask-RESTful version:

from flask import Flask
from flask_restful import Resource, Api

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

usersList = ['Aaron', 'Bianca', 'Cat', 'Danny', 'Elena']

class UsersList(Resource):
    def get(self):
        return { 'users' : [ user for user in usersList  ] }, 200


class UserById(Resource):
    def get(self, id):
        return { 'username': usersList[id] }


class UserByName(Resource):
    def post(self, name):
        usersList.append(name)

        return { 'message': 'New user added'}


api.add_resource(UsersList, '/users')
api.add_resource(UserById, '/user/<int:id>')
api.add_resource(UserByName, '/user/<string:name>')

app.run()

Using Flask-RESTful, I cannot get a single resource to serve multiple related endpoints like GET /user/<int:id>, GET /user/<string:name>, GET /user/<int:id>/friends etc. And I don't know if creating new classes for simple sub-resources is a good practice because I'll probably end up with many classes. Due to this reason, I'm more inclined towards using just Flask since only functions are defined and the endpoints can be freely defined as per my needs.

Keeping the above in mind, is it okay to create many classes for sub-resources in Flask-RESTful? Or am I better of using Flask? Or Flask-RESTful provides some really good advantages over Flask?

Shahlin Ibrahim
  • 1,049
  • 1
  • 10
  • 20
  • [see this hope this will help you](https://stackoverflow.com/questions/37783919/flask-restful-vs-flask-restless-which-should-be-used-and-when) – Sagar Dec 14 '18 at 10:31
  • @Sagar I have gone through this, the reason I'm not using Flask-RESTless is because I'm not using any SQL database. Instead I'm using DynamoDB which I don't think SQLAlchemy supports – Shahlin Ibrahim Dec 14 '18 at 11:10

4 Answers4

6

REST is a pretty flexible architecture, but there's a few points worth thinking about in your approach using just Flask, which Flask-RESTful is encouraging you away from:

  1. By convention, a GET on a single resource (e.g. /users/1234) is by a unique identifier for the resource. The name of a user can't be guaranteed to be unique, so it would be risky to have it as an identifier within the URI (e.g. /users/joe).

  2. When you access users within a collection, it's better to stick with the plural noun throughout (not, as you show in your Flask example, /user/...).

  3. When you're creating and using POST, unless your client is specifying the id (in which case it has to be able to guarantee uniqueness, so pretty much the only valid id would be a UUID), you can post to just the collections URI (e.g. /users/).

Either will work, but with Flask-RESTful you'll find that when you follow those guidelines, your class matches your resources much more closely and you won't see the proliferation of classes you describe.

A very similar use case is demonstrated at https://flask-restful.readthedocs.io/en/latest/quickstart.html#full-example.

rich carter
  • 103
  • 6
  • Let's say, I don't have the name endpoint but instead I want something like `GET /user/20/friends`. With Flask-RESTful, I'd have to create a new class for that. And if I wanted to see all the users friend requests (for example), that would mean I create many classes for each sub resource. Is that considered bad or it's okay to create many classes for related resources? – Shahlin Ibrahim Dec 14 '18 at 11:16
  • 1
    You're describing nested resources, and yes it's fine to have a new class map to the nested resource. It looks like "more stuff" and not very pythonic, but it actually makes things much clearer when you know that for each resource there will be a class. – rich carter Dec 14 '18 at 11:32
  • Yeah, I was just worried about it getting very crowded. But since you said it makes it easier, guess I'll just go with Flask-RESTful or Flask-RESTplus – Shahlin Ibrahim Dec 14 '18 at 11:44
4

Not sure why no one mentioned the fact that standard Flask is also REST-API enabled i.e. you really don't need to import the REST package to avail something that is missing in standard Flask package.

You are absolutely free to choose whichever you want depending upon your comfort level and any method chosen shouldn't affect your end-result functionality.

I understand that we can be inclined towards using something that is meant for a specific job but sometimes, in coding world, comfort matters regardless of how many extra lines of code you have to write.

Hope this answers your query.

PanDe
  • 831
  • 10
  • 21
  • 1
    This is so true! I've created some REST APIs using Flask for personal projects and now I'm doing for my work and looking for some best practices I came across Flask-Restful/Flask-Restplus. Although flask-rest* looks the right tool for the job, the standard Flask architecture looks much more cleaner to me and I don't know if swagger support worth the change – dsenese Oct 14 '21 at 21:57
3

I would recommend you to use Flask-RESTplus instead, that will give you full Swagger support.

In regards of just using Flask, I would say getting the Swagger functionality is a big one to choose Flask-Restplus also.

StefanE
  • 7,578
  • 10
  • 48
  • 75
  • 1
    This is very similar to Flask-RESTful. Nonetheless, is it okay to have multiple classes for sub resources? I just feel that, there would be too many class declarations (not sure if it's a bad design) – Shahlin Ibrahim Dec 14 '18 at 11:13
  • 3
    Flask-RESTplus is considered deprecated. Use Flask-RESTx instead https://github.com/python-restx/flask-restx – Titouan Feb 18 '21 at 18:16
0

In my personal opinion, Flask-RESTful abuses the use of OOP, and it doesn't feel an intuitive approach for me. I prefer "plain Flask" for REST API development over Flask-RESTful.

Ben Zayed
  • 548
  • 4
  • 7