Building a (simple) REST application with Pecan (pecanpy)

Post to Twitter

Pecan is a lean Python web framework inspired by CherryPy, TurboGears, and Pylons (Pyramid). According to the main Pecan documentation page: “Pecan was created to fill a void in the Python web-framework world – a very lightweight framework that provides object-dispatch style routing. Pecan does not aim to be a “full stack” framework, and therefore includes no out of the box support for things like sessions or databases (although tutorials are included for integrating these yourself in just a few lines of code). Pecan instead focuses on HTTP itself”. Today, I’m going to focus on a few REST capabilities of Pecan.

For those who like to track OpenStack developments you might be interested to know that in September of 2013 Pecan was added to Stackforge and is currently being used by the Ceilometer OpenStack project as well as being planned to be used in future API versions for existing OpenStack projects. Recently, at the OpenStack Hong Kong conference there was some talk regarding a unifying WSGI framework. Some OpenStack projects like Marconi use a web framework called Falcon. I’m not going to focus on pros and cons of either of these. If you would like to also see a small tutorial on Falcon check out my prior article here.

Using Python 2.7.x and virtualenv let’s create a project for this example application. I’m assuming your using Linux (OS X will work as well).

$ virtualenv pecanrest-proj
$ cd pecanrest-proj
$ source bin/activate
$ pip install pecan
$ pecan create pecanrest
$ cd pecanrest
$ python setup.py develop

This will create a project with the default boilerplate files and folders. You don’t have to use the pecan create command, but for this article it will help us get bootstrapped easier than rolling it all by hand.

Make sure everything is working by starting the default application:

$ pecan serve config.py

You should see something similar to this:

Starting server in PID 14821
serving on 0.0.0.0:8080, view at http://127.0.0.1:8080

Go ahead and hit the endpoint with a web browser and then CTRL-C to kill the app when your finished.

Let’s create a REST based application now. Go into the root.py file located in pecanrest/controllers/ and open it up for editing.

root.py

We are going to remove all the default generated code and replace it with what will end up being the first piece of our REST application. The application will be quite dumb to start with by simply returning a version in JSON format. Modify the root.py to look like this:

from pecanrest.controllers import v1

class RootController(object):
    v1 = v1.VersionController()

In the same folder as the root.py file add another file called v1.py and insert the following code:

import pecan
from pecan import rest

class VersionController(rest.RestController):
    @pecan.expose('json')
    def get(self):
        return {"version": "1.0.0"}

Start the application:

$ pecan serve config.py

You should see this on the console:

Starting server in PID 15270
serving on 0.0.0.0:8080, view at http://127.0.0.1:8080

Go ahead and hit the endpoint preferably with a REST client such as Poster: http://localhost:8080/v1

Screen Shot 2014-01-18 at 11.03.18 PM

Assuming that is working for you let’s move onto designing a really simple REST API. We are only going to support a simple GET to fetch some data and then stub out DELETE, POST, and PUT. First, let’s refactor our project a little.

In the controllers folder add another folder called api. Inside the api folder create two files, one called order.py and the other called api.py. Inside the controllers folder delete the v1.py file.

Note: Make sure anytime you create a new folder inside a Python project you add a __init__.py file. Why? See here.

Go into the root.py and setup the controller like this:

from pecanrest.controllers.api import api

class RootController(object):
    api = api.ApiController()

Go into the api.py file and add the following:

from pecanrest.controllers.api import order

class ApiController(object):
    orders = order.OrdersController()

Finally, we can modify the order.py file in the api folder:

import pecan
from pecan import rest, response

class OrdersController(rest.RestController):

    @pecan.expose("json")
    def get(self):
        return {
            "100A": "1 bag of corn",
            "293F": "2 bags of potatoes",
            "207B": "1 bag of carrots"
        }

    @pecan.expose()
    def post(self):
        # TODO: Create a new order, (optional) return some status data
        response.status = 201
        return

    @pecan.expose()
    def put(self):
        # TODO: Idempotent PUT (return 200 or 204)
        response.status = 204
        return

    @pecan.expose()
    def delete(self):
        # TODO: Idempotent DELETE
        response.status = 200
        return

Note: Pecan also offers other ways to handle JSON, see here for more information.

Your endpoint will now be: http://127.0.0.1:8080/api/orders

Run the application and hit it with a GET/POST/PUT/DELETE.

Console results

This is at least a starting point. Be sure to check out the documentation on Pecan to dive deeper into the framework.

Post to Twitter

This entry was posted in Open Source, OpenStack, Python, REST. Bookmark the permalink.

4 Responses to Building a (simple) REST application with Pecan (pecanpy)

  1. joe says:

    Awesome tutorial….I need to work on more example codes on json parsing.
    Could you please suggest me few sites on PECAN other than Pecan docs available.

  2. Chad Lung says:

    @Joe,

    I don’t know of any other websites with Pecan content but it is used throughout several OpenStack projects so you can check the following to see how they use it:
    https://github.com/openstack/ceilometer
    https://github.com/openstack/barbican
    https://github.com/stackforge/solum

    Chad

  3. joe says:

    Thanks for your reply and suggestions chad…just had one doubt ,without using a Poster add on to submit the GET,PUT,POST etc in the above tutorial .The normal browser
    if I hit with http://127.0.0.1:8080/api/orders in the browser Url it is a get request and i get JSON respone…..How to enter the url for the POST/PUT/DELETE request in the browser…to get the similar o/p as i get when i poster when i hit post/delete/put

    I tried something like this http://127.0.0.1:8080/api/orders/?&method=POST to get the respone response.status = 201 same tried for PUT and DELETE but it is not working…
    Could you please answer my final doubt on this wonderful tutorial.

  4. Chad Lung says:

    @Joe,

    I don’t know off hand how you could do this through a browser. A web browser itself by default (no add-ons) is going to just do HTTP GET requests. Typically you would use cURL or an add-on like Poster, Fiddler, etc. With those tools you can easily control the HTTP verbs toward the endpoint.

    Chad

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>