9.3. Producing Web Service Data
If you've set up your application using RESTful controllers, then you're already halfway toward acting as a web service. Your application is set up with a standard API that other applications will be able to hit. The second half involves producing machine-readable code in the expected formats.
9.3.1. Producing XML
You've already seen the first part of the Rails XML response mechanism — it's part of the RESTful controller scaffold. As a reminder, here it is again:
def index
@recipes = Recipe.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @recipes }
end
end
The render :xml method call immediately turns around and calls the to_xml method on the argument. Rails defines to_xml for most classes, including ActiveRecord::Base, Array, and Hash. For example, the default XML result for a Recipe object would look something like this:
<?xml version=\"1.0\" encoding=\"UTF-8\"?> <recipe> <cached-ingredient-string></cached-ingredient-string> <cached-tag-list>grandma, chicken, fred</cached-tag-list> <created-at type=\"datetime\">2007-08-05T20:03:33-05:00</created-at> <description>Yummy!</description> <directions>Things</directions> <id type=\"integer\">1</id> <servings>3</servings> <title>Grandma's Chicken Soup</title> <updated-at type=\"datetime\">2007-09-04T23:04:45-05:00</updated-at> <user-id type=\"integer\">2</user-id> </recipe>
The default XML for an array of recipes is similar, but it wraps the whole thing in a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access