Monthly Archives: September 2010

Setting custom request headers with objective resource

For the last few evenings I have been working on a native Mac app for Staging that talks to a Rails restful API. Rather than write the code access the resource URLs myself I thought it would be pretty cool to use Objective Resource, the Objective-c library for accessing Rails-style restful APIs, from the site:

ObjectiveResource is an Objective-C port of Ruby on Rails’ ActiveResource. It provides a way to serialize objects to and from Rails’ standard RESTful web-services (via XML or JSON) and handles much of the complexity involved with invoking web-services of any language from the iPhone.

There are a couple of problems with this approach however. First ObjectiveResource is designed to work on iOS (iPhones, iPod touches and iPads) only, and second it expects access to be controlled by a username and password. The API for Staging uses an X-API-Token HTTP header sent with each request.

Getting ObjectiveResource to work on native Mac

This was pretty simple, just replace all instances of

#import <UIKit/UIKit.h>

with:

#import <AppKit/AppKit.h>

So far nothing has broken.

Getting ObjectiveResource to send a custom header

This was a little trickier and required some more invasive code changes. In Connection.h declare two new methods:

And define them in Connection.m:

Next you need to modify the request that gets called for every GET request:

The addition here is basically a for loop to loop over every header that we have configured and add them to the request object. Finally somewhere before you make any requests in your code:

Done! Now every request that GETs made will have the custom header sent along with it. You can obviously set any number of arbitrary headers using this method too, you aren’t limited to my X-API-Token. It is left as an exercise to the reader to implement the same for POST requests.

It would be nice to see these changes rolled into the ObjectiveResource framework in some way.

Tagged , ,
Follow

Get every new post delivered to your Inbox.