0
votes

In my application, I would like to allow user introduce a url of instagram, and then automatically retrieve the embed code of it.

I found this reference: https://www.instagram.com/developer/embedding/#oembed

When I try the given example (https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN) in my Chrome browser, I get the json with the code I am looking for.

However, if I try this from the rails console:

Net::HTTP.get_response(URI("https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN"))

I get this:

#<Net::HTTPMovedPermanently 301 MOVED PERMANENTLY readbody=true> 

I saw that instagram have a new API, but I don't want to make user authenticate from instagram.

Is there a way to do it?

2
So it redirects? The response should return the redirect location, what do you get it you follow the redirect? - j-dexx
There is no redirection url in the response - guyaloni

2 Answers

3
votes

You can use oembed gem by soulim. nice and clean way to get embed code

In case of instagram it goes like

include following line in your gem file

gem 'oembed'

next

bundle install

create a helper class

class InstaApi
  include Oembed::Client

  def endpoint_uri
    'http://api.instagram.com/oembed'
  end
end

Now you can use

instClient = InstaApi.new
info = instClient.fetch('http://instagr.am/p/BUG/')

to Get your embed code

embed_code = info["html"]
1
votes

Using the docs

def fetch(uri_str, limit = 10)
  # You should choose a better exception.
  raise ArgumentError, 'too many HTTP redirects' if limit == 0

  response = Net::HTTP.get_response(URI(uri_str))

  case response
  when Net::HTTPSuccess then
    response
  when Net::HTTPRedirection then
    location = response['location']
    warn "redirected to #{location}"
    fetch(location, limit - 1)
  else
    response.value
  end
end

str = "https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN"
response = fetch(str)
redirected to https://api.instagram.com/publicapi/oembed/?url=http://instagr.am/p/fA9uwTtkSN
redirected to https://www.instagram.com/publicapi/oembed/?url=http://instagr.am/p/fA9uwTtkSN
redirected to https://api.instagram.com/oembed/?url=http://instagr.am/p/fA9uwTtkSN
=> #<Net::HTTPOK 200 OK readbody=true>

response.body
=> # JSON response

So just follow the redirects.