Steve Jackson

Ruby, Rails, Vim, and various other musings
31 Aug 2011

Facebook photo downloading script

I wrote a quick script using the Facebook Graph API to download photos tagged of myself. It’s pretty easily modifiable to grab any other objects from your graph, too.

Go to the Graph API explorer and generate an access token with the permissions you need. In this instance: user_photos, user_photo_video_tags. Just use that token when you run this ruby script and you’re golden:

require 'json'
require 'net/http'

def fetch(output_dir, username, photo_limit, access_token)
  url = "https://graph.facebook.com/#{username}/photos?limit=#{photo_limit}&access_token=#{access_token}"
  uri = URI.parse(URI.encode(url))
  
  http_session = Net::HTTP.new(uri.host, uri.port)
  http_session.use_ssl = true
  
  response = http_session.request(Net::HTTP::Get.new(uri.request_uri))

  jsonresult = JSON.parse(response.body)
  result_data = jsonresult["data"]

  if result_data.nil?
    puts "No data to parse. Maybe you've got an invalid access token or uri?"
    return
  end

  for entry in result_data
    system "wget --directory-prefix='#{output_dir}' #{entry['source']}"
  end
end

fetch('my-photos', 'YOUR_FACEBOOK_IDENTIFIER', 2000, 'YOUR_ACCESS_TOKEN')