RESTful Integration: Part One

Last time, we setup a simple controller in Rails that accepted
POX data. Now lets go the next
step and add a hypermedia format to our service and message. Our
original service used a media type of “application/xml” but we really
should use something different. The media type “application/xml” has a
well defined processing model and semantics. The deal breaker here
is “application/xml” does not define a semantic meaning for links. (We
will cover the importance of links in a future post.)  What we really
want is a custom media type so we can assign our own semantics to the
message.

Our media type for this example will be “application/vnd.rogue+xml”.
(The “vnd” namespace is reserved for creating proprietary media types.)
The first thing we need to do is configure our Rails application to
recognize our new media type. We do that by adding the following two
lines to the mime_types.rb file located in config/initializers.

1
2
3
Mime::Type.register "application/vnd.rogue+xml", :rogue

ActionController::Base.param_parsers[Mime::Type.lookup("application/vnd.rogue+xml")] = :xml_simple

The first line registers our new media type and assigns a symbol to it.
The second line configures a parser for our new media type. Since we are
still using XML to represent our data, I decided to use the xml_simple
parser. Next, we need to add some new code to the respond_to block of
our controller. This works the same way it did in our original example.

1
2
3
4
5
6
7
8
format.rogue {
quote = params[:quotation]
@quotation.customer = quote[:customer]
@quotation.quote_amount = quote[:quote_amount]
@quotation.status = quote[:status]
@quotation.save
render :xml => @quotation
}

Finally, in order to test this we change our curl script to use our new
media type.

1
curl -H "Accept: application/vnd.rogue+xml" -H "Content-Type: application/vnd.rogue+xml" -d @quote.xml http://localhost:3000/quotations/new

Next time we will take a look at adding additional semantic information
to our data and look at how we can use that information to represent
application state.