Positive Incline Mike Burrows (@asplake) moving on up, positively

February 18, 2010

PathTo for Python gets a JSON-capable HTTP client

Filed under: Web Integration — Tags: , , , , , , , , — Mike @ 1:55 pm

…and it works!

>>> import path_to
>>> app = path_to.open_app('http://example.com', format='json')
>>> app.login.post(credentials, expected_status=302)
>>> print app.products.resource_template
products      products     GET, POST http://example.com/products{.format}
  new_product new_product  GET       http://example.com/products/new{.format}
  {product}   product      GET, PUT  http://example.com/products/{product}{.format}
    edit      edit_product GET       http://example.com/products/{product}/edit{.format}
>>> product = app.products['Foo'].get(expected_status=200).parsed
>>> product['description'] = 'Updated!'
>>> app.products['Foo'].put(product, expected_status=302)
>>> app.products['Foo'].get(expected_status=200).parsed['description']
u'Updated!'

OK, so it wasn’t really “example.com”, and the updated product wasn’t called “Foo”, but the rest is for real.

In stages:

0) The Pylons-based server has the JSON-capable @validate (un)decorator of my previous post and DescribedRoutesMiddleware from DescribedRoutes installed in its wsgi stack.

1) Create a client-side proxy to the app. Following link headers published by the app, it finds the ResourceTemplates description, which it retrieves in JSON format.

>>> import path_to
>>> app = path_to.open_app('http://example.com', format='json')

The format='json' is a small red herring here, it’s simply remembered for later.

2) Log in by posting credentials, expecting a 302 status (a failed attempt would return a 200 and the validation errors in the body). The client handles cookies automatically behind the scenes.

>>> app.login.post(credentials, expected_status=302)

3) View a friendly representation of the metadata (or rather the part that relates to products):

>>> print app.products.resource_template
products      products     GET, POST http://example.com/products{.format}
  new_product new_product  GET       http://example.com/products/new{.format}
  {product}   product      GET, PUT  http://example.com/products/{product}{.format}
    edit      edit_product GET       http://example.com/products/{product}/edit{.format}

4) Get a product identified by ‘Foo’ and return the JSON payload parsed into a Python dict.:

>>> product = app.products['Foo'].get(expected_status=200).parsed

Behind the scenes it has expanded the “http://example.com/products/{product}{.format}” template seen previously into “http://example.com/products/Foo.json”, using the remembered format parameter and the supplied ‘Foo’ key which is assumed to correspond to the required product parameter.

5) Update the local product representation and send it back (it gets converted back to JSON along the way):

>>> product['description'] = 'Updated!'
>>> app.products['Foo'].put(product, expected_status=302)

6) Finally, demonstrate that it was successful!

>>> app.products['Foo'].get(expected_status=200).parsed['description']
u'Updated!'

January 20, 2010

Small steps along my personal Python roadmap

Filed under: Web Integration — Tags: , , , — Mike @ 1:25 pm

Three new things tried in recent days:

  1. Packaging a Python module
  2. Using doctest in anger (tweaking doctests in Routes doesn’t really count)
  3. Publishing a package to PyPi

For #1, I used setuptools, kick-started by Ian Bicking’s excellent presentation (the official docs are good too).  Completely painless, and it pretty much covers #3 too.  All in all I would say that it was easier than building and publishing a Rubygem.

Re #2, doctest isn’t going to replace regular unit tests for me, but for describing a public API I think it’s excellent.  In the case of LinkHeader, exercising the public API doesn’t leave much else – it’s a very simple package.  Here’s a small excerpt:

>>> parse('<http://example.com/foo>; rel="foo bar", <http://example.com>; rel=up; type=text/html')
LinkHeader([Link('http://example.com/foo', rel='foo bar'), Link('http://example.com', rel='up', type='text/html')])

which demonstrates how to parse a link header into something a client can easily interrogate.

LinkHeader will be used by DescribedRoutes to add discoverability to web apps and by PathTo clients in order to discover and interact with application resources.  All of this works in Ruby already of course; my current personal project is to replicate it in Python with support for the Pylons web framework.  The Link Header standard is progressing meanwhile, with a new version published only this week.

August 4, 2009

described_routes is Rack middleware

Filed under: Web Integration — Tags: , , , , , , , — Mike @ 12:01 pm

Last week I received this:

#described_routes could make beautiful middleware

Why didn’t I think of that?

So I took a quick look at Rack, found there was almost nothing to learn, and over the weekend made the change. And it was well worth it: integrating described_routes into your Rails application is now much easier. There’s no need to modify your routes (the middleware recognizes and serves requests to /described_routes automatically) or your controllers (the discovery protocol’s link headers are added automatically to other requests). In fact the old integration method looks so ugly by comparison that I’ve deprecated it – it’s *that* embarrassing!

Now, run-time integration needs only this modification to your environment.rb‘s Rails::Initializer.run block:

require 'described_routes/middleware/rails'
Rails::Initializer.run do |config|
  ...
  config.middleware.use DescribedRoutes::Middleware::Rails
  ...
end

Revised instructions (compare with the old):

  1. Install the described_routes gem for the server
  2. Add build-time integration to the server (a one-liner to add some useful Rake tasks)
  3. Add run-time integration to the server (just the environment.rb modification above)
  4. Install and run path-to (for an “instant” client API)
  5. Profit!

Yes, it’s for Rack for Rails

The sharp-eyed reader will have noticed that despite the move to Rack, we’re still discussing a Rails integration. What about described_routes for other Rack-aware or Rack-based frameworks?

Most of the new middleware’s functionality exists in an abstract class DescribedRoutes::Middleware::Base but it needs two methods implemented for each framework:

  1. get_resource_templates – get named routes from the application and convert to ResourceTemplates
  2. get_resource_routing – map a request to a ResourceTemplate and its parameter list

In DescribedRoutes::Middleware::Rails:

  1. get_resource_templates hooks into described_routes code originally based on ‘rake routes’, and
  2. get_resource_routing extracts the controller name, action name and path parameters from a Rack environment member ‘action_controller.request.path_parameters’ populated by Rails as it processes the request – our stuff must happen afterwards.  The route name is reverse-mapped from the controller and action name.[1]

It should be clear now that both methods are necessarily framework-specific; indeed Rack does not provide routing itself.

The test of described_routes‘s underlying framework-neutrality will be its integration with a framework other than Ruby on Rails. This should be easier to achieve now than previously; perhaps someone with more knowledge and need than me will beat me to it (please be my guest!). I’m tempted meanwhile to double the challenge and attempt it in Python for WSGI-based frameworks (wish me luck!).

[1]Actually it’s a shame that Rails doesn’t make the request’s route name or route object available anywhere – is there anyone else who would use it?

August 3, 2009

One link to rule them all

Filed under: Uncategorized,Web Integration — Tags: , , — Mike @ 11:22 am

A quick demonstration of the described_routes discovery protocol is in order. It’s all done with link headers, one per resource.

Starting with some arbitrary resource in the application:

$ curl --silent --head http://localhost:3000/users/dojo | grep Link
Link: ; rel="describedby"; meta="ResourceTemplate"
$ curl --silent --head http://localhost:3000/described_routes/user?user_id=dojo | grep Link
Link: ; rel="index"; meta="ResourceTemplates"

So after the first HEAD request we have the location of the resource’s ResourceTemplate metadata; after the second we have the location of the site ResourceTemplates (plural) metadata.

A HEAD request to the site metadata location merely confirms (via the meta tag) what we already knew:

$ curl --silent --head http://localhost:3000/described_routes | grep Link
Link: ; rel="self"; meta="ResourceTemplates"

On the root resource, a single HEAD request links us to the site metadata location directly:

$ curl --silent --head http://localhost:3000 | grep Link
Link: ; rel="describedby"; meta="ResourceTemplates"

After that, it’s up to the client.

When you create a path-to client thus:

app = PathTo::DescribedRoutes::Application.discover("http://localhost:3000/users/dojo")

path-to discovers the site metadata and GETs it, specifying JSON as the acceptable format. The JSON response is converted to basic Ruby objects and used to initialize the Application object app. The client now knows the application’s resource structure:

app.users['dojo'].uri
=> "http://localhost:3000/users/dojo"

and we’re back where we started!

July 23, 2009

New link_header gem

Filed under: Web Integration — Tags: , , , , , — Mike @ 9:26 pm

My latest project on github and Rubyforge is link_header, a small rubygem for parsing and generating HTTP link headers as per the latest spec draft-nottingham-http-link-header-06.txt.

Usage

The usual install:

sudo gem install link_header

The library’s LinkHeader and LinkHeader::Link classes follow a pattern established in the ResourceTemplate and ResourceTemplate classes in that they offer easy conversions both to & from Ruby primitives, i.e. Arrays, Strings etc. This in turn makes them easy to prettyprint, convert to & from JSON and YAML, create from test fixtures, and so on. [Aside: @kevinrutherford and I discussed this idea on Twitter a few days ago in response to his blog post “factory method in ruby“. It’s worth a read.]

Link attribute names can appear more than once, so I have chosen a list of attribute/value pairs rather than a hash to represent link attributes. Link objects do however have an #attrs method that will lazily generate a hash if that’s convenient (it’s left to you to decide whether it’s safe!). There’s an example of this below.

So:

require "link_header"
require "pp"

#
# Create a LinkHeader with Link objects
#
link_header = LinkHeader.new([
  LinkHeader::Link.new("http://example.com/foo", [["rel", "self"]]),
  LinkHeader::Link.new("http://example.com/",    [["rel", "up"]])])

puts link_header.to_s
#=> <http://example.com/foo>; rel="self", <http://example.com/>; rel="up"

link_header.links.map do |link|
  puts "href #{link.href.inspect}, attr_pairs #{link.attr_pairs.inspect}, attrs #{link.attrs.inspect}"
end
#=> href "http://example.com/foo", attr_pairs [["rel", "self"]], attrs {"rel"=>"self"}
#   href "http://example.com/", attr_pairs [["rel", "up"]], attrs {"rel"=>"up"}

#
# Create a LinkHeader from raw (JSON-friendly) data
#
puts LinkHeader.new([
  ["http://example.com/foo", [["rel", "self"]]],
  ["http://example.com/",    [["rel", "up"]]]]).to_s
#=> <http://example.com/foo>; rel="self", <http://example.com/>; rel="up"

#
# Parse a link header into a LinkHeader object then produce its raw data representation
#
pp LinkHeader.parse('<http://example.com/foo>; rel="self", <http://example.com/>; rel = "up"').to_a
#=> [["http://example.com/foo", [["rel", "self"]]],
#    ["http://example.com/", [["rel", "up"]]]]

Later…

My next programming task will be some minor refactoring on described_routes and path-to take advantage of this new gem. The driver behind this all is an efficient discovery protocol and a significant reduction in the number of links reported by default – I realised that it was wasteful to produce multiple links on every request that are (let’s be honest) be of no interest at all to clients, when just one of those links points to metadata that carries that same information and more! Then for those server apps that generate the correct headers, a short one-liner will initialize a path-to client given the address of any resource served by the application, i.e. without special knowledge of the location of the app’s metadata resources.

Refactoring aside, the described_routes part of this is done (so servers support the protocol already); I just need to finish path-to part to take advantage of it on the client side.

I can’t make any promises about timelines at the moment (new job starts soon) but a Python version should be forthcoming soon(ish) also. Meanwhile, enjoy the Ruby version if you can!

Powered by WordPress