As I had some troubles finding out how to show some of my own Flickr photos on this site using the Flickr API and Ruby on Rails I thought it would be useful to write it down in a small tutorial.
Flickr lists 3 possible Ruby frameworks for their API. After trying flickr.rb (no longer available) and not being able to login I decided to switch to rFlickr as it seems the most popular one.
Start with installing the rFlickr library. You may need to uninstall a previous library if you installed another one earlier.
gem install rflickr
Flickr doesn’t use the username/password combination as most other API's do. An application can ask for permissions which the user has to grant. A token is returned when this is done allowing the application to connect the next time so we'll only have to do this once. Apply for a key at the Flickr website and remember the key and the shared secret. I use a “Web Application” key as I want to use it for my blog.
Start your development environment:
./script/console
Next load the newly installed rFlickr module and ask for a Flickr frob using the API key and shared secret you got earlier.
>> require 'flickr'
=> []
>> flickr = Flickr.new('/tmp/flickr.cache', YOUR_KEY, YOUR_SECRET)
=> #<Flickr:0x...
>> flickr.auth.login_link
=> 'http://flickr.com/services/auth/?api_sig=a07a7...'
This will return a URL you need to copy & paste in your browser to allow the application to read, write and delete your photos. If you don’t need all this permissions your can add the “perms” parameter for a less greedy permissions. Use the following if you only need read access to the photos:
>> flickr.auth.login_link(perms='read')
Allow the application to access your photos when you open the URL. You can request the forb we need and make sure to to keep it for now.
>> flickr.auth.getFrob
=> '7215760...'
Now we’ll need a token. The token is more permanent as the frob but we need the forb to get one. Finally cache the token:
>> flickr.auth.getToken('YOUR_FROB')
=> #<Flickr::Token:0x...
>> flickr.auth.cache_token
=> 154
Now it’s time to do something more useful with the token. What about showing the thumbnails of the 6 last added photos? We’ll need your NSID which is the strange number in your Flickr URL that looks like 26227936@N00.
def flickr
require 'flickr'
photos = Array.new
flickr = Flickr.new('/tmp/flickr.cache', 'YOUR_KEY', 'YOUR_SECRET')
photo_list = flickr.people.getPublicPhotos('YOUR_NSID','',6)
photo_list.each do |photo|
photos.push( {'id' => photo.id, 'source' => photo.sizes[:Square].source} )
end
return photos
end
Look, you now have an array with the last 6 posted public photos and their ID.
This post is open source. Did you spot a mistake? Ideas for improvements? Contribute to this post via Github. Thank you!