Push to IMGUR and get tiny url with RUby

After a long absence from blogging snippet of code or anything interesting (lately I was kind of busy with work and personal issues to solve), I’d like to share with you something that I created months ago but I hadn’t the time to publish: a ruby code to publish new images to imgur.

As you can find on WikipediaImgur is an online image hosting service founded by Alan Schaaf in 2009 in Athens, Ohio (not Greece as I imagined first by reading it). Imgur describes itself as “the home to the web’s most popular image content, curated in real time by a dedicated community through commenting, voting and sharing. It offers free image hosting to millions of users a day, and a comment-based social community.

So far so good, but how can we interact with it? Imgur exposes APIs to interact with the entire Imgur infrastructure via a standardized programmatic interface. Using Imgur’s API, you can do just about anything you can do on imgur.com, while using your programming language of choice, in my case Ruby.

Lets move ahead! First of all you need to register to have an account, then navigate to the imgur API http://api.imgur.com and read the documentation. The following step consist in the creation of the API KEY.

Under settings > applications click on create you own


And register you application:


For tests purposes just pick random values, in my case:

Application name: imgTest
Authorization type: OAuth authentication without callback
Description: test

Fill the captcha and submit the form.


Great! Now you have the Client-ID and the token to perform programmatic access to your account.

#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'open-uri'
require 'json'
require 'base64'
def web_client
  http = Net::HTTP.new(API_URI.host, API_URI.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
API_URI = URI.parse('https://api.imgur.com')
    :image => '3/image',
    :upload => '/3/upload'
img = File.open("your-image.jpg", "rb") {|io| io.read}
params = {:image =>  Base64.encode64(img),
          :gallery => "gallery",
          :name => "name"
request = Net::HTTP::Post.new(API_URI.request_uri + ENDPOINTS[:image])
request.add_field('Authorization', API_PUBLIC_KEY)
response = web_client.request(request)
puts JSON.parse(response.body)['data']['link']

The JSON response contains the tiny URL to the uploaded image:


We can improve the code by adding the album and gallery parameters.

In my next post I’ll explain how to automatic post to linkedin accounts using the imgur script and other libraries.

Tagged , ,