Inspired? No home

Get Flickr Id and display photos with Hpricot in Ruby on Rails

To utilize the Flickr API you need the Flickr Id not the Flickr username. I have not found a method for finding the Flickr Id based on username in the Flickr API, so I have created a simple scaping method that find a hidden form field in the Flickr profile for a specified user.

This code assumes you have a model with attributes ‘flickr’ (flickr username) and ‘flickr_id’. It will trigger whenever ‘flickr’ is updated and then set ‘flickr_id’.

First you need the Hpricot gem: sudo gem install hpricot

before_update :flickr_change

def flickr_change if self.flickr_changed? require ‘hpricot’ require ‘open-uri’ doc = open(“http://www.flickr.com/people/#{self.flickr}/”) { |f| Hpricot(f) } f = doc.search(“//input[@name=’w’]”) unless f.empty? && !f.first self.flickr_id = f.first.attributes[‘value’] else self.flickr = nil self.flickr_id = nil flash[:error] = “Unable to find Flickr username” raise “Unable to find Flickr username” end end

rescue OpenURI::HTTPError => e puts “The page is not accessible, error #{e}” self.flickr = nil self.flickr_id = nil self.errors.add(:flickr, “not found”) end </code>

Then in my person_helper I have create a little method that will return a hash with the 10 latest photos. The extras parameter takes a comma seperated value for setting which values to return. I have specified to return the URL for square and small photo sizes. See the Flickr photo search method in the API for more info.

def flickr_photos(person) require 'open-uri' doc = open("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOUR_API_KEY&user_id=#{person.flickr_id}&per_page=10&extras=url_s,url_sq") { |f| Hpricot.XML(f) } return doc.search("//photo").collect{|p| { :title => p.attributes["title"], :url_sq => p.attributes['url_sq'], :url_s => p.attributes['url_s'] } } end

If you prefer Ruby syntax instead of using Hpricot to generate and process requests you could use one of the Flickr gems that are available: Flickraw and Flickr_fu. I had problems installing then when using Ruby 1.9 so I made the small script above instead.

If you just want to get your own Flickr Id you can use idgettr.com

Written on 26 February 2010.
blog comments powered by Disqus