Ruby on Rails 3 – Flickr API for photo search

This post shows how to show images using Flickr API on your Rails 3 application. Some notables:

  • You need to get flickr API key from Flickr website
  • You do not need any plugin or gem to be installed for rails 3
  • This tutorial explains two things
    • How to get images using Flickr API
    • How to display them using a simple slideshow

Here is some sample code that goes into your controller. You can call this function from any of the actions of your controller. Let us say, you want to show the pictures of a city along with other usual details. Your show function will give a call to flickrAPI(city).

function flickrAPI(city)
require ‘net/http’
require ‘uri’
require ‘rexml/document’

uri = URI.parse( “http://api.flickr.com/services/rest/” )
params = {‘method’=>’flickr.photos.search’, ‘api_key’=>’36590fb7531f20c1d91ff431d38e3a51’, ‘accuracy’=>’10’, ‘sort’=>’relevance’, ‘media’=>’photos’, ‘tags’=>city}

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
request.set_form_data( params )

# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ ‘?’ + request.body )

response = http.request(request)
xml_data = response.body
doc = REXML::Document.new(xml_data)

doc.root.elements[1].each_element { |e|
if e.attributes[‘title’] =~ /#{Regexp.escape(city)}/i
url = “http://farm”+e.attributes[‘farm’]+”.static.flickr.com/”+e.attributes[‘server’]+”/”+e.attributes[‘id’]+”_”+e.attributes[‘secret’]+”.jpg”;
@flickrUrl.push(url)
end
}

end

Next is your show.html.erb. You need to display the images, preferably in a slide show. Here goes the code that you have to append:

<div id=”scroll”>
<% @flickrUrl.each do |url| %>
<img src=”<%=url%>” height=”240″/>
<%end%>
</div>
<script type=”text/javascript”>
$(‘#scroll’).cycle()
</script>

Do not forget to add ‘jquery’ and ”jquery.cycle-lite’ in your view/layout/application.html.erb.
Resources:

One thought on “Ruby on Rails 3 – Flickr API for photo search

Comments