Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

A Coder's Journey

From educator to programmer.

Object = 'What We Talk About When We Talk About Third Party API's'.new

I ended my last post stating you should wrap your desired API’s methods in your own instance methods. While this is true, I left out the whole why of it all. How dare I!

Allow me, to give you a hint…

You see, everything, and I do mean EVERYTHING(!) in Ruby is an object, including our dear complicated API’s.

Without further ado, I’d like to introduce you to my API object:

1
2
3
4
5
require 'open-uri'

class InstagramWrapper

end

You may have noticed that I required open-uri. Using this is an easy-to-use wrapper for net/http, net/https, and net/ftp, and is included in the ruby standard library, meaning, if you are in a rails app, you do not need to require open-uri.

Now, because we are dealing with the instagram API call, itself–as an object–we need to initialize it and that means, we need to ask ourselves some seriously existential questions.

This is not a pipe

What makes an API call an API call?

…or, in less abstract terms, what exactly does an API call need to be an API call?

This depends on what kind of API call you are making.

If you want to make a call on behalf of a user, chances are, you will need to use OAuth, to get permission to user the user’s specific id. If you just want to get the result for a certian tag search or really, anything unrelated to a specific user, you will more than likely, not need the user to authorize, your application. For the purposes of this tutorial, let’s say you just want to get all the instagrams for a specific tag search.

To bring our API call to life we need to initialize the client_id (a key you get by registering your application with instagram).

1
2
3
4
5
6
7
8
class InstagramWrapper
  attr_accessor :client

  def initialize
    @client = Instagram.client(:client_id => ENV["INSTAGRAM_CLIENT_ID"])
  end

end

Now you can go into your rails console and type:

1
playing_with_my_new_api_class = InstagramWrapper.new

Which will return the InstagramWrapper object, the API call itself. Don’t be shy. Ask what methods are available to you:

1
playing.methods

And the first one is client. Keep asking questions (They keep you young at heart ❤️ ).

1
playing.client.methods

And there it is!!!! tag_search(!!!!). Just do it.

1
playing.client.tag_search("everythingsanobject")

One smart cookie has tagged this. Neat-o. Lets add this method to our Instagram API object.

1
2
3
4
5
6
7
8
9
10
11
class InstagramWrapper
  attr_accessor :client

  def initialize
    @client = Instagram.client(:client_id => ENV["INSTAGRAM_CLIENT_ID"])
  end

  def number_of_tags(tag)
    client.tag_search(tag)
  end
end

And there you have it. Your very own, fully functional API object tightly wrapped in a InstagramWrapper class.

Present

You’re welcome.