Pylons tip #1 - RESTful Web API decorators

October 21, 2008 at 10:15 PM | categories: Technical, Python | View Comments |

I've been playing around with implementing REST-ful HTTP APIs under Pylons recently. Something I find myself doing frequently is writing code to restrict the allowed methods for a given URL. For example, a read-only service should generally only allow GET actions while a write service should generally require POST. Its easy to end up with code like this sprinkled in each controller action:

    # writeservice only accepts POST method requests
    def writeservice(self):
        if request.method != 'POST':
            abort(405,  headers=[('Allow', ['POST'])]
        # ...
        pass
One of the handy modules provided by Pylons is REST-ful decorators. This module provides a simple method decorator called pylons.decorators.rest.restrict. This decorator does essentially the same as the above conditional, but normalises it to a shorter block:
from pylons.decorators import rest

    # writeservice only accepts POST method requests
    @rest.restrict('POST')
    def writeservice(self):
        # ...
        pass
While in the above example, there is not much space savings, when dealing with various API entry points, the @rest.restrict decorator can make things much clearer, less error-prone and even save a modest amount of lines of code. Handy!

Niall O'Higgins is an author and software developer. He wrote the O'Reilly book MongoDB and Python. He is the co-founder of BeyondFog, Inc which makes Strider Brilliant Continuous Deployment. Strider is a hosted Continuous Integration & Deployment service for Node.JS and Python.

blog comments powered by Disqus