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( “” )
params = {‘method’=>’’, ‘api_key’=>’36590fb7531f20c1d91ff431d38e3a51’, ‘accuracy’=>’10’, ‘sort’=>’relevance’, ‘media’=>’photos’, ‘tags’=>city}

http =, uri.port)
request =
request.set_form_data( params )

# instantiate a new Request object
request = uri.path+ ‘?’ + request.body )

response = http.request(request)
xml_data = response.body
doc =

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


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″/>
<script type=”text/javascript”>

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

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