Bootstrapping REST

In this article I’m approaching REST from the perspective of client/server interaction, most especially (and slightly unusually I think) on the needs of the client and you, the client’s developer. I hope you find it helpful.

A caveat (no apology): my interest is in structure and navigation. HTTP has mechanisms already for clients and servers to negotiate content types and I’ve made a conscious design decision to rely on their existence. In other words, I ignore it completely here. Orthogonality is a wonderful thing!

We start at the beginning:

The completely hand-crafted client

At the most extreme, you’re working against an undocumented, unsupported server API that lacks regular structure. Any complexity implies significant reverse-engineering effort, made worse if you’re tracking a moving target. If you’re lucky though, you’ll be working against a supported and stable API.

Relying on regularity

Servers built using frameworks such as Rails (and even many that aren’t) will tend to exhibit some predictable patterns. The details may be framework-specific, but a collection resource, say “users”, can be expected to support these (or similar) operations and subresources:

GET, POST         http://www.example.com/users
GET               http://www.example.com/users/new
GET, PUT, DELETE  http://www.example.com/users/{user_id}
GET               http://www.example.com/users/{user_id}/edit

and a nested collection resource (each user’s articles, say) can be expected to follow a similar structure, rooted on a specific user resource.

GET, POST         http://www.example.com/users/{user_id}/articles
GET               http://www.example.com/users/{user_id}/articles/new
GET, PUT, DELETE  http://www.example.com/users/{user_id}/articles/{article_id}
GET               http://www.example.com/users/{user_id}/articles/{article_id}/edit

Armed therefore with just the knowledge of the user and articles collections, your client’s internal object model might easily support expressions such as

app.users
app.users.new
app.users[user_id]
app.users[user_id].edit
app.users[user_id].articles
app.users[user_id].articles.new
app.users[user_id].articles[article_id]
app.users[user_id].articles[article_id].edit

You’ll pay a price when the application departs from its usual pattern, but most of the time you’ll be fine. In fact for many client applications the edit and new are irrelevant, so all you need is the basic hierarchical structure and knowledge of the representations you can GET, PUT, POST there, also how to DELETE things.

Model-driven development

One approach to speeding application development is to abstract out that object model and generate skeleton code for both client and server from some common, logical representation. Not only are you spared the task of building the object model, but (given the right toolset) you can expect to have the web client functionality baked in for you. Most importantly, it’s much cheaper to track any changes made on the server.

The downside? You are now tied to a toolset. That might be a price worth paying if you’re in control of both client and server (for an internal application, say), but for many this will be unpalatable.

The no-model option

[Stick with me - this apparent digression makes metadata-driven clients easier to introduce!]

Dynamic languages make it possible to support expression like

app.users[user_id].articles.new

even if your app object doesn’t actually have a users member (method, attribute or property) and articles and new exist nowhere either. See [1] and [2] to read how (generally) this can be done in Ruby and Python, and [3] for a description of path-to [4], an actual client that can work this way.

Even without these dynamic features, a similar effect can be achieved with operator overloading. This, for example, is perfectly valid Java:

app / users / member(user_id) / articles / _new

The objects returned by such expressions can easily have a URI representation, request methods and so on.

But beware! Suppose a user resource defines an “up” link. Take for example

app.users["dojo"].up

To which of these URIs (below) does this expression refer?

http://www.example.com/users/dojo/up

http://www.example.com/users

We’ll come back to this issue later.

Metadata-driven clients

You can take the no-model approach and validate each navigation against it, so that for a non-existent path foo,

app.foo

raises an error just as the model-driven version would have done. To your client application code, this implied object model looks no different to the generated one, even though (in a way) it doesn’t really exist! I like to think of this as the model-driven approach turned inside-out – instead of running code generated from a model, we run code that interprets a model.

If that metadata comes from the server (so much better than a build-time configuration step), you’re getting closer to that RESTful goal of application interaction driven by links, or

Hypertext as the engine of application state (HATEOAS) [5]

But before claiming this goal genuinely you will need to address a couple of issues that we’ve glossed over so far:

  1. how to generate URIs for collection members, for example turning users["dojo"] into http://example.com/users/dojo
  2. how to generate URIs for navigations like up and first

The cleanest answer to the first issue is the URI Template (a parameterised URI with a standardised syntax), sourced (naturally) from the server. With Fielding’s quote in mind it’s clear that the resolution to the second issue must lie also in server-provided information. In fact we’ll see both issues come together as we understand that the problem really isn’t one of describing URI structure but instead one of describing resource relationships and their manifestations in links.

URI Templates and Resource Templates

A URI Template that maps users["dojo"] into http://example.com/users/dojo might look this this:

http://example.com/users/{user_id}

The syntax isn’t that important (the draft standard looks set to change significantly), and yes, we’ve seen them here already without introduction. They’re pretty self-documenting and (with a good library implementation) easy to use. If you stick to a standard there’s nothing unRESTful about them – having your application create a URI from template is really no different from a browser creating a URI as the result of GET-based HTML form.

In more complex cases – in particular where there is a mixture of mandatory and optional parameters – it’s advantageous to wrap the URI Template in some basic metadata. WADL [6] is a well-supported example of this idea (well almost – see the comments [7]) ; another is my own Resource Template format [8] (actually more a logical schema than a format since it’s available in JSON, YAML and XML).

WADL and Resource Templates typically describe an entire application, each element describing a class of resource, its relationships, its URI template (so that relationships can be turned into links), parameters, supported HTTP methods and so on.

Integrated with Rails, Resource Templates are generated by the server at run-time from the application’s routes, information already available. Although (most typically) they can be generated and consumed for the whole application in one go, they can be generated for a single resource already pre-populated with that specific resource’s known parameters.

At last: links!

From those pre-populated, resource-specific Resource Templates we can generate links – as HTML or XML elements or as HTTP headers – that our client can consume and navigate, resource by self-described resource. Every resource becomes a potential entry point to a virtual application that can easily span multiple servers. Finally, we got there: true hyperlink-based client/server interaction, and where the framework support exists, for very little effort too.

Discussion

In this article I have described the journey I travelled myself over a period of weeks following my decision to expose a complex existing application to scripting via HTTP. For me, technology-neutrality was a determining principle, and selecting HTTP and REST was an easy decision, first to make and then to sell. A proof of concept and a good demo based on a hand-crafted object model came quickly; metadata and templates were the result of some serious refactoring. Resource Templates came after I left the project, as did Rails integration (not a project requirement) and the path-to client in both Ruby and Python.

At the time of writing, link generation is supported on the server side but not yet on the client. The purist in me likes the fact that it is theoretically possible and will strive to keep it that way; the engineer in me is for the moment content with slurping up a whole application’s worth of metadata in one go and thereafter restricting interactions and payloads to the application level. Even as a purist, I see elegance in a simple metadata format, avoidance of hand-coded generation of URIs, respect for the power of HTTP and the orthogonality of formats; and if you believe as I do that RESTfulness lies in how clients and servers interact and not just in how server resources support the HTTP methods, I’ve probably succeeded in taking it further than most.

References

  1. Dynamically extending object behaviour in Ruby and Python [positiveincline.com]
  2. Programmatically adding methods to classes and objects: more Ruby/Python comparisons [positiveincline.com]
  3. path-to is born: nice client-side APIs to web applications in Ruby, also articles tagged path-to [positiveincline.com]
  4. path-to (Ruby) and path-to-py (Python) [github.com]
  5. Representational State Transfer (REST) (Chapter 5 of Architectural Styles and the Design of Network-based Software Architectures) [www.ics.uci.edu]
  6. Web Application Description Language [wikipedia.com]
  7. Partial template expansion in described_routes (comments)” [positiveincline.com]
  8. described_routes: hierarchical, framework-neutral and machine-readable descriptions of Rails routes [positiveincline.com], described_routes (Ruby) and described_routes-py (Python) [github.com]

Resolutions

In my previous post I was casting around for an alternative to type as the name of a link header attribute, since in the standard this refers to a content type, not the “logical” type of the resource pointed to by the link.

I have decided to go with role, borrowed from XLink. I know that we’re not dealing with XML here and XLink isn’t wildly popular, but it’s documented, accepted and understood, so why reinvent the wheel?

Consistent with both XLink and the existing rel attributes, I’ve made these role attributes contain URIs, as in this example:

Link: <http://example.com/users/dojo>; rel="self"; role="http://example.com/described_routes#user",
           <http://example.com/described_routes/user>; rel="describedby"; role="http://example.com/described_routes#described_route",
           <http://example.com/described_routes/user?user_id=dojo>; rel="describedby"; role="http://example.com/described_routes#ResourceTemplate",
           <http://example.com/users>; rel="up"; role="http://example.com/described_routes#users",
           <http://example.com/users/dojo/edit>; rel="edit"; rel="http://example.com/described_routes/user#edit"; role="http://example.com/described_routes#edit_user",
           <http://example.com/users/dojo/articles>; rel="http://example.com/described_routes/user#articles"; role="http://example.com/described_routes#user_articles"

You can think of this in terms of entities and relationships in the ER model:

  role="http://example.com/described_routes#user_articles"

identifies a target entity (“user_articles” in this example, named after its Rails route) within the overall schema, and

  rel="http://example.com/described_routes/user#articles"

identifies a relationship (“articles”) within the description of the source entity (“user”).

These URIs are globally unique, and even if they are never dereferenced by the client (i.e. the client isn’t interested in the ResourceTemplate metadata there – shame on them!), these values can be used by clients to select links reliably.

Postscript

One of my sources of both good practice and inspiration has been Tim Berners-Lee’s Design Issues. I hadn’t got to the Metadata Architecture article until after drafting the above, and it’s quite gratifying to read it now.  Tim makes the ER comparison too, but rather than rehash that I will quote some of his key principles:

Metadata about one document can occur within the document, or within a separate document, or it may be transferred accompanying the document.

Link headers and link elements pointing to ResourceTemplate documents exemplify all three possibilities.

The URL space is an appropriate space for the definition of attribute names

Not only appropriate, but a lot more powerful than arbitrary tokens.  My initial plan to use simple names for rel and type attributes were definitely misguided.

As much as possible of the syntax and semantics should be able to be acquired by reference from a metadata document.

Within the scope of defining navigations around a web application I think this is achieved successfully.  A lot can be done by the client even without the metadata document, though clients will still need help in constructing URIs for members of collections.  I think there would a be place for the ResourceTemplate format (or something very much like it) even if there was a standard for URI Templates in link headers, but that’s a whole new article, perhaps my next one.

Link header dilemmas

I received a very reasonable answer to my question (thank you Phil), but as a result of trawling through 12 months of archive came to realise that I’d misunderstood the guidance (or rather the relative lack thereof) regarding the use of the type link attribute.  The spec cites RFC 4287 The Atom Syndication Format and it appears that I have abused it by populating it with resource template names (sourced from Rails route names).  My fault entirely, lesson learned.

I’ll need to choose a more appropriate name for it therefore – either that or remove it altogether!  Possibilities:

  • name?  I quite like this, but is it too generic?
  • resourcename? Is this any better than name?
  • routename? Accurate when driven from Rails, but otherwise too implementation-specific I think
  • linkname? I quite link this too, but why not call the linkname on a link just name?
  • target?  Already taken, or at least too reminiscent of the target frame/window attribute.  Perhaps I’m on a better track here though? targettype maybe?

Aarrgghh!  We know that naming is hard; naming a name is doubly so.  I’ll sit on this for a while and hope that either inspiration or feedback comes…

Link headers, link elements, and REST

The house move looms (still no date yet, frustratingly) so I’ve had less time for programming (or blogging for that matter!).  I do however have an experimental and unreleased enhancement to the Ruby version of described_routes that generates link elements (for the <head> section of your html) or the yet-to-be-standardized link headers completely automatically.  Integrating them into your Rails application requires just a one-liner per layout or controller (or you can do all controllers in one go).  Drop me a line if you would like to play with it.

I have one question outstanding on the new spec (see it here on the ietf-http-wg list archives) but I have to say that I’m pretty happy with it all.  It takes the ideas of Partial template expansion in described_routes and adds a standardised way to relate content and metadata, making it even easier clients to navigate web applications without necessarily slurping up the entire site’s schema in one go.  It allows interaction to be 100% RESTful (HATEOAS and everything), and even if you prefer not to go that way as a client you can at least be confident that the application will be transparent, self-documenting and well-behaved.

Ringing true: robust planning and Agile

asplake: semi-accidentally stayed subscribed to Mike Cohn’s comment feed – I’m keeping it for good now http://bit.ly/JWPP8 #agile

Mike’s thought-provoking post Why there should not be a release backlog from early February is still attracting comments four months later, and it prompted me to go back to his Agile Estimating and Planning book and re-read chapter 17, Buffering Plans for Uncertainty.

Sometimes I hear people talk about projects deadlines and commitments as though they’re somehow alien to Agile. Back in the real world though, it’s reassuring to have on the bookshelf a book by an Agile luminary that rings true to experience and teaches (very readably) a practical approach to robust project planning.  It’s really not all that hard to do, and you have my Release Calculator and Wiggle Room Calculator to help!

The word “control” doesn’t appear in the index of Mike’s book.  That’s a statement of fact rather than a big criticism and an excuse to mention another great book, Making Things Happen (Mastering Project Management) by Scott Berkun.  These two books together would be a good foundation for any project manager, with the small caveat that won’t go far enough for people who have to operate in very prescriptive environments (not my scene at all, let’s be honest!).

Any more book or blog recommendations out there for the agile project manager (books on project management specifically)?  Do they ring true for you?

Programmatically adding methods to classes and objects: more Ruby/Python comparisons

In Dynamically extending object behaviour in Ruby and Python we explored techniques for extending object behaviour dynamically by catching calls to undefined methods and having the target objects respond in some interesting way. In this sequel we achieve similar results by a very different (put perhaps more straightforward) approach, adding methods to existing classes and objects ahead of time programmatically.

I’ve avoided here approaches that simply involve generating program source as strings and then eval-ing it in some way. This  can be effective, but it’s uninteresting and perhaps a bit inelegant! Instead, we use closures, in the form of blocks, lambdas and nested functions.

Straight then to code. First comes Ruby, which I’ve done for 5 or so years on and off, then Python – for 3 weeks maybe? With that admission out there I’ll be as fair as I can!

Ruby

class Hello
  attr_reader :name

  def initialize(name)
    @name = name
  end

  # define a method named x that says hi to x
  def self.def_hi(x)
    define_method(x) { "Hi #{x} from #{name}" }
  end

  # handy helper - see http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html
  def metaclass; class << self; self; end; end

  # uniquely for the object, define a method named x that says hi to x
  def def_obj_yo(x)
    metaclass.send(:define_method, x) { "Hi #{x} from #{name}" }
  end

  def_hi "everyone"
end

h1 = Hello.new("h1")
h2 = Hello.new("h2")

Hello.def_hi("foo")
h1.def_obj_yo("baz")

puts h1.everyone      #=> "Hi everyone from h1"
puts h2.everyone      #=> "Hi everyone from h2"
puts h1.foo           #=> "Hi foo from h1"
puts h2.foo           #=> "Hi foo from h2"
puts h1.foo           #=> "Hi bar from h1"
puts h2.foo           #=> "Hi bar from h2"
puts h1.baz           #=> "Hi Baz from h1"
puts h2.baz           #=> NoMethodError: undefined method ‘baz’ for #

Here, the everyone and foo methods are defined on the class as normal instance methods, and baz is defined as a method on h1‘s “metaclass” (thanks to _why for the helper), making it specific to the h1 instance.

In each case, define_method does the job of creating and installing the method on a class; the subtlety is in the way the blocks (the {...} bits) capture the x parameters for later use.

Newbie Python

class Hello(object):
    def __init__(self, name):
        self.name = name

    @classmethod
    def def_hi(cls, x):
        'define a method named x that says hi to x'
        setattr(cls, x, lambda self: "Hi %s from %s" % (x, self.name))

    @classmethod
    def def_hello(cls, x):
        'define a method x that says hi to x'
        def say_hello(self):
            return "Hello %s from %s" % (x, self.name)
        setattr(cls, x, say_hello)

    def def_obj_yo(self, x):
        'uniqely for the object, add a callable attribute named x that says hi to x'
        setattr(self, x, lambda: "Yo %s from %s" % (x, self.name))

h1 = Hello("h1")
h2 = Hello("h2")

Hello.def_hi("foo")
Hello.def_hello("bar")
h1.def_obj_yo("baz")

print h1.foo()           #=> "Hi foo from h1"
print h2.foo()           #=> "Hi foo from h2"
print h1.baz()           #=> "Yo baz from h1"
print h2.baz()           #=> AttributeError: 'Hello' object has no attribute 'baz'

To be honest, I’m not sure how idiomatic this Python code is, but it certainly works in Python 2.6.2. The reason I mention the version is that older documentation refers to a now-deprecated module “new”, that contains tools similar to Ruby’s define_method. My code is remarkably simple for what it achieves: it just adds lambda objects (in def_hi and def_obj_yo) or function objects (in def_hello) and sets them as attributes of the class or object. Again, we’re relying on those closures to capture the x parameters indefinitely.  The “hi” and “hello” versions aren’t very different (except in length);  sometimes a lambda is too restrictive and a nested function is more appropriate.

I’m 99.9% sure satisfied now (I was rather less sure as I posted the first drafts of this article; I’ve since read the relevant parts of the Language Reference) that the foo objects are proper methods in the strictest sense, though they definitely do behave like them. It’s probably fair to say though that though baz isn’t really a method; self isn’t set as a result of calling the method – it’s just another variable captured in the lambda. Sneaky! If we copied it onto another object, self would still refer to h1.

Comparison

These two lines of Ruby:

  attr_reader :name
  def_hi "everyone"

are executed as the class definition is created. They are very simple examples of how we can define and use what look like new keywords but are in reality just calls to class methods. More complicated examples accept blocks, providing nice API-defined extension points for subclasses to add custom behaviour. Ruby excels in its ability to define APIs not just for their functionality but for their sheer prettiness from the user’s (especially the extender’s) perspective.

Even disregarding cosmetic details such as the optionality of parentheses in Ruby, I was unable to execute similar code within the scope of the Python class definition. Please do correct if me if I’ve got this wrong – having commented this morning (perhaps prematurely) on Yehuda Katz’s interesting article The Importance of Executable Class Bodies it would be good to clear this up!

[UPDATE: yes you can execute arbitrary code within the scope of the class definition, but it's not quite as simple as calling class methods - in fact I still haven't found a way to access the class object as it's being defined (perhaps it doesn't exist yet!).  The gory details of something that looks pretty close are in 157768: Automating simple property creation (from 2002, perhaps superseded since)]

There is however still a certain elegance to the Python idea (explored more fully last time) of methods being just function-valued (or callable) attributes of objects. No special syntax needed (I don’t think I can ever learn to love Ruby’s class << self idiom) and I love the ease with which function objects can be obtained, installed and invoked, and how, nested within other functions, they can be closures.

On balance? Ruby does seem capable of supporting the nicest APIs (DSLs even), but there’s a simplicity to Python that perhaps makes for more understandable code internally. There’s an interesting balance there to be struck, though neither one wins on a knockout. We’re down now to the level of personal preference, though even without choosing a winner it has definitely been a beneficial experience to have taken on a new language in a serious way. It changes you!

Alternative URI Templates implementation in Python; fun with decorators

I’ve added uri_templates.py to the described_routes-py repository.  Feature-wise, it differs from Joe’s in that it supports a partial expansion mode (see this post for motivation).  Implementation-wise, it’s all done with regexps – no special parsers required.

There are a couple of missing features (I own up to them in the docstring) but they probably won’t get fixed. Not only do I not need them, but we’re expecting the spec to undergo some some significant change soon and it would probably be wasted effort.

Fun with decorators

For a bit of Python newbie fun, I used a decorator to populate the operator dispatch table:

def operator(name):
    def save_operator(func):
        operators[name] = func
        return func
    return save_operator

@operator('opt')
def op_opt(arg, variables, params, encoding, partial):
    etc

They then get called by:

    operators[operator](arg, variables, params, encoding, partial)

Easy! Perhaps this is overkill, but it seems nicer than techniques like calling functions via constructed function names and it might allow new operators to be added from outside the module.

This must be the simplest example of parameterised decorators you’re ever likely to find as there’s no function wrapping involved. The one thing to understand is that operator('opt') returns a new function that “remembers” the name ‘opt’.

Dynamically extending object behaviour in Ruby and Python – a quick warts-and-all comparison

In path-to, the seemingly innocuous expressions

app.users['dojo'].articles['behind-the-scenes'].edit
app.user('dojo')

are relying on behaviour that is added dynamically. Here, users, articles, edit and user don’t actually exist as defined properties or methods – they are caught and simulated behind the scenes, driven by metadata (descriptions of web resources) loaded at runtime.

Because of fundamental differences in the way object member access works in Ruby and Python, the path-to implementations differ quite significantly under the covers. As promised in my previous post, I explore some of the issues here.

Object member access

Fundamentally different!

  • All Ruby object access is via methods, some of which may be parameterless accessors
  • All Python object access is via properties, some of which may be methods

So,

foo.bar

in Ruby invokes a method that must be either parameterless or whose parameters all have default values defined. In Python it retrieves a property, which may be a value or a function object. Importantly, that function object is not invoked – only foo.bar() would do that.

Adding behaviour dynamically with method_missing and __getattr__

Recall:

  • All Ruby object access is via methods, some of which may be parameterless accessors

In Ruby, when you invoke a non-existent method (e.g. app.users), Ruby calls the target object’s method_missing, which you can override to do something interesting and return a value (all Ruby functions return values, even if only nil).

  • All Python object access is via properties, some of which may be methods

In Python, an attempt to retrieve a non-existent property results in a call to __getattr__. Again, you can override this to do something interesting and return a value. But what if the thing returned needs to behave like a method?

Chaining with Python’s callables

Callables in Python are objects that can be invoked as functions. These include the obvious things like functions and methods (yes they’re objects too), but also includes lambdas, classes (invoking a class creates an instance) and potentially even regular user-defined objects.

In path-to-py, I wanted to emulate a style that you get for free in Ruby, and (thankfully) it turns out to be not so hard in Python either. The challenge is this: when following a resource relationship that doesn’t need parameters, e.g. from the users collection to its new input form:

app.users.new

I didn’t want to force this kind of style, e.g.

app.users().new()

even though any of these navigations may take optional parameters, such as

app.users.new(format="json")

The trick is to make each of these objects callable by defining a __call__ method. Then app.users.new returns one object, and the (format="json") returns another, slightly more specialised one. It’s a particular example of chaining, which is – as you may have gathered already – at the heart of both versions of path-to.

Lambdas

In the case that the callable returned by Python’s __getattr__ must take arguments, the answer is more straightforward: return a function or a function-like object. In path-to-py, we return a lambda that invokes the object’s child method, passing all arguments (positional and keyword) to it, thus:

return lambda *args, **kwargs: self.child(attr, *args, **kwargs)

Some have criticised Python’s lambda for being limited to single expressions. I’m fine with it myself; the simple case looks very neat, and the general case is more than adequately covered by nested functions. And Ruby isn’t without its warts either:

l = lambda {|foo| ... }
l(bar)      # doesn't invoke l
l.call(bar) # ugh
l[bar]      # what???

And nested functions in Ruby don’t work as closures either. Much as I love Ruby, Python deserves better press in this regard I think!

Indexing collections

This works similarly in both languages, though this time my niggles are with Python. If you want an object to behave like an array or dictionary/hash, simply define the [] operator in Ruby or the __getitem__ method in Python. In path-to, these always return new objects (yes, it’s that chaining pattern again).

Python’s warts: you can declare your method thus to allow arbitrary parameters:

def __getitem__(self, *args):

but its behaviour is inconsistent. Sending it one argument will give you the expected one-element args tuple; two or more arguments give you a one-element tuple containing a tuple! In path-to-py, there’s code to detect this and where necessary flatten args before passing it on. And don’t bother with keyword arguments (adding **kwargs to the declaration) – any attempt to use it, e.g.

app.users['dojo', format='json']

actually gives a syntax error. In path-to-py, you can choose between one of these forms (below) instead. The first two are entirely equivalent; the second looks uglier but removes a level of chaining:

app.users['dojo'](format='json')
app.users['dojo'].with_options(format='json')
app.users['dojo', {'format': 'json'}]

Conclusion

Niggles aside, adding behaviour dynamically in Ruby and Python isn’t all that scary really! Their underlying models are surprisingly different, yet there’s no lack of power in either one.

New on github: path-to-py (path-to for Python)

Best to go to the path-to-py repository where the README is nicely rendered on the front page, but here’s a sneak preview:

Initialise a client with the metadata shown in the appendix at the end of this file. Typically provided by the server in JSON or YAML.

>>> from path_to import Application
>>> app = Application(...)

Chaining, indexing, following relationships between resources:

>>> print app.users['dojo'].edit

http://example.com/users/dojo/edit

Positional and named parameters:

>>> print app.user_article('dojo', 'foo', format='json')

http://example.com/users/dojo/articles/foo.json

I’ve improved the described_routes-py README (not to mention fixing the odd bug) also.

As I hinted in my previous post, I’m taking to Python much more readily than I expected.  The Python ports of both path-to and described-routes are much cleaner than their Ruby originals (the benefit of rewriting, not Ruby’s fault), are just as nice to use, and (Rails integration aside) have almost equivalent functionality already.  There are some significant differences under the covers but I’ve not yet missed a Ruby feature.  In a future post I’ll write up some of the more interesting changes.