简体   繁体   中英

Flask-Restfull over Flask-Restless

I am new to Python and exploring the Flask framework.

I am using Flask Restful for developing a simple Rest based API. Now the greatest challenge that i found was using the SQL Alchemy Model classes to JSON. Today i have came across Flask-Restless that seemingly provides this. So what should i choose. I managed to convert Flask Restful to provide JSON output by using to_dict functions in my model classes like this

class JSONSERIALIZER(object):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

Kind Regards

Restful is db agnostic, so you can use it with the trendy NoSql databases, whereas Restless will only work with Sql databases (because of its dependency on sqlalchemy). But if you do end up using a Sql database and are okay with sqlalchemy, then Restless will provide more out of the box for you.

fwiw, my personal favorite is Restless+Postgres.

Edit: to show how little you have to do to build a rest api with restless, I just made https://github.com/findjashua/flask-restless-example/blob/master/server.py

Flask-restless definitely has more out-of-the-box, and implements SQLAlchemy's Query API at the Web-service level of abstraction, allowing for complex queries via a GET request. For instance:

http://localhost:5000/api/book?q={"filters":[{"name":"is_available","op":"==","val":true},{"name":"author_id","op":"==","val":1}]}

Is equivalent to:

session.query(Book).filter(Book.author_id==1, Book.is_available == True).all()

Further, Flask-restless has a Beta release that is aiming to comply with JSONAPI v1.0 which may prove to be very powerful.

I wrote a quick tutorial on how you can bootstrap a Flask API using SQLAlchemy and Flask-Restless. It also dives a bit deeper than the above example, explaining how related objects are handled gracefully by Flask-restless. You can find it here:

http://thelaziestprogrammer.com/sharrington/web-development/sqlalchemy-defined-rest-api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM