Steve Klabnik changelog.com/posts

Hyperresource: a hypermedia API client for Ruby

Any of you who know me aren’t surprised about me posting this story: it’s right up my alley!

Basically, hyperresource is intended to be a general hypermedia client. What’s that mean? It can work with any API that happens to use one of the media types it supports. Right now, that’s just HAL+JSON, but more will be added in the future.

What’s that mean in terms of code? Well, here’s an example from the README:

api = HyperResource.new(root: 'https://api.example.com')
# => #<HyperResource:0xABCD1234 @root="https://api.example.com" @href="" @namespace=nil ... >
root = api.get
# => #<HyperResource:0xABCD1234 @root="https://api.example.com" @href="" @namespace=nil ... >
root.response_body
# => { 'message' => 'Welcome to the Example.com API',
#      'version' => 1,
#      '_links' => {
#        'self' => {'href' => '/'},
#        'users' => {'href' => '/users{?email,last_name}', 'templated' => true},
#        'forums' => {'href' => '/forums{?title}', 'templated' => true}
#      }
#    }
jdoe_user = api.users.where(email: "jdoe@example.com").first
# => #<HyperResource:0x12312312 ...>

How does it know how to look up those users? Well, there’s a users link relation on in the response, and it has a templated URI as its href attribute. This lets the client reflect and know how to look up users by their email or last name.

The power of this generic tooling is that we no longer have to think about how to parse HAL, how to interpret the response… we have this one library which works with any HAL-powered API.

The biggest drawback of hyperresource is that it’s read-only at the moment, nothing but GET. But it shows a lot of promise, and I’m excited to see this kind of stuff pop up in the wild. Everything I see points to 2013 as the year of example code for hypermedia services.

Check it out on GitHub.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00