views:

206

answers:

2

Im building my first app in rails and I would like to call Flickr's API

I know I can use flickr-fu, rflickr or other gem but I want to do it myself from scratch to learn

Say, for example, I want to call flickr.photos.comments.getList that returns the comments for a photo. The arguments are api_key and photo_id. I have both.

I will get the response as an xml

<comments photo_id="109722179">
<comment id="6065-109722179-72057594077818641" author="35468159852@N01" authorname="Rev Dan Catt" datecreate="1141841470" permalink="http://www.flickr.com/photos/straup/109722179/#comment72057594077818641"&gt;
Umm, I'm not sure, can I get back to you on that one?</comment>
</comments>`

I want to store the data received by calling that method into a variable comments that I can access the data using, for example,

comments.all.first.author_name = "Rev Dan Catt"

or

comments.all.first.content = "Umm, I'm not sure, can I get back to..."

How can I do this? Please be patient (sorry for the noob question)

A: 

First you need some kind of an XML parser to handle the data you got. Nokogiri is a much used parser, but it might be a little too much. In that case find a more simple one.

This should be enough

But if you really want to the be represented as you suggest in your example, you need to (recursively) iterate through your XML document and put it in some structure. Take a look at Ruby access magic to see how you can dynamically build such a structure. Another possibility is to create classes for all the groups of details (as flickr-fu) does, which is much more efficient since the data is known on beforehand.

PS You can cheat a bit by looking to other solutions, this way you will still learn to do it yourself, but you do not need to re-invent the wheel completely. In fact combine the idea of several implementations and you might come up with something even better!

Veger
+1  A: 
include 'rubygems'
include 'httparty'

class Flickr
  include HTTParty

  base_uri 'api.flickr.com'

  def self.getPhotos(uid)
    return get('/services/rest/', :query => {
      :method => 'flickr.people.getPublicPhotos',
      :api_key => 'api key goes here',
      :user_id => uid})
  end
end

and then call

Flickr.getPhotos('12345678')
Victor P