Web API's are broken, deal with it! (part 1)

By: Sam Barnes

Tags:

  • activeresource
  • api
  • library
  • ruby

Web based API's come in all shapes and sizes, not all of them conform to RESTful conventions: incorrect response codes, different response formats, odd resource name spacing, and problematic transport layers plague many of the API’s we as developers have to deal with.

Trying to make ActiveResource handle these inconsistencies can lead to nasty hacks to get things working. Going down the HTTParty route makes things clearer but still feels kinda rough and ready.

Considering our options and looking at the current issues we came up with a new approach on how we interact with API’s using Ruby.

Rather than lots of magic, as per ActiveResource (and cousins), we took the view that the interactions between the remote and the local resource should be very transparent and easy to understand.

A very simple example:

# pull in the contents of record 8894 from the
# external API into a new Contact instance
@contact = Contact.pull(8894)
# ... make some changes
@contact.save  # save the local copy to the db (optional)
@contact.push  # push the changes back to the remote API

In the example above we use two familiar concepts to users of git: push and pull. These two operations are remote, they either pull in remote data or push it back.

If this was an ActiveRecord object find and save would work as usual (and expected). A clear degree of separation between remote and local means that data only gets transferred either to or from the remote resource when we request it to.

Finding out more

This simple example doesn't really do the library we have been developing justice so in subsequents posts we will be expanding upon the concepts and code samples in more detail. In the mean time please do subscribe to the RSS feed to keep updated and watch this space.


About the Author

Sam Barnes

blog comments powered by Disqus