开发者

How do I make a uber-simple API wrapper in Ruby?

I'm trying to use a super simple API from is.gd:

http://is.gd/api.php?longurl=http://www.example.com

Which returns a response header "HTTP/1.1 200 OK" if the URL was shortened as expected, or "HTTP/1.1 500 Internal Server Error" if there was any problem that prevented this. Assuming the request was successful, the b开发者_StackOverflow社区ody of the response will contain only the new shortened URL

I don't even know where to begin or if there are any available ruby methods to make sending and receiving of these API requests frictionless. I basically want to assign the response (the shortened url) to a ruby object.

How would you do this? Thanks in advance.


Super simple:

require 'open-uri'

def shorten(url)
  open("http://is.gd/api.php?longurl=#{url}").read
rescue
  nil
end

open-uri is part of the Ruby standard library and (among other things) makes it possible to do HTTP requests using the open method (which usually opens files). open returns an IO, and calling read on the IO returns the body. open-uri will throw an exception if the server returns a 500 error, and in this case I'm catching the exception and return nil, but if you want you can let the exception bubble up to the caller, or raise another exception.

Oh, and you would use it like this:

url = "http://www.example.com"
puts "The short version of #{url} is #{shorten(url)}"


I know you already got an answer you accepted, but I still want to mention httparty because I've made very good experiences wrapping APIs (Delicious and Github) with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜