Skip to content
January 9, 2013 / jphoward

Intermission–REST API in Python with Flask-Restless

In my End to end web app in under an hour tutorial I have been using C# for the backend and SQL Server for the DB. What if you’d rather use something else? Easy! For example, here’s how to port what we’ve done in parts 1-4 to Python. We’ll use the handy Flask-Restless library to create the API, along with Flask-Sqlalchemy to handle ORM duties for us. We’ll use sqlite as our DB in development, since it’s easy to get up and running. You should switch to something more appropriate in production (such as postgresql), although I won’t be covering that here.

Creating the model

To start with, import the appropriate modules, create and configure your flask app (including selecting an appropriate path for your sqlite db), and create your Todo model class.

import flask
import flask.ext.sqlalchemy
import datetime

app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

class TodoItem(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    todo= db.Column(db.Unicode)
    priority = db.Column(db.SmallInteger)
    due_date = db.Column(db.Date)

Now you are ready to create your API endpoint.

import flask.ext.restless

db.create_all()
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

manager.create_api(TodoItem, 
    methods=['GET', 'POST', 'DELETE', 'PUT'], results_per_page=20)

app.run()

That’s all you need! Try running that, and go to /api/todo_item in your browser. (Note that flask-restless turns CamelCase class names into underscore_separated names). You may also want to prepopulate your table with some data. I’ll leave that for you to do before moving on to the next section.

Updating the controller

Flask-Restless uses a somewhat different format for both its request and its response. Therefore we have to modify a few things in our controller (templates and directives however should not need to change). I created the following method in my ListCtrl, in order to simplify creating a request in the format that Flask-Restless expects:

var make_query = function() {
    var q = {order_by: [{field: $scope.sort_order, direction: $scope.sort_desc ? "desc": "asc"}]};
    if ($scope.query) {
        q.filters = [{name: "todo", op: "like", val: "%" + $scope.query + "%"} ];
    }
    return angular.toJson(q);
}

I also modified $scope.search() to call make_query, and account for the different response format in Flask-Restless.

$scope.search = function () {
    var res = Todo.get(
        { page: $scope.page, q: make_query() },
        function () {
            $scope.no_more = res.page == res.total_pages;
            if (res.page==1) { $scope.todos=[]; }
            $scope.todos = $scope.todos.concat(res.objects);
        }
    );
};

Finally, I created a small method to call when creating the controller, or when changing sort order:

$scope.reset = function() {
    $scope.page = 1;
    $scope.search();
};

That’s basically all that is required to have this up-and-running in Python!

Advertisements

One Comment

Leave a Comment
  1. Samuel Mukoti / Mar 5 2014 9:51 pm

    Hi,

    Do you have examples on how i can do PUT and UPDATE Todos?

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: