Skip to content

Instantly share code, notes, and snippets.

@ostinelli
Last active December 13, 2018 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostinelli/e3e5d00daeed40089a708e52c25a1085 to your computer and use it in GitHub Desktop.
Save ostinelli/e3e5d00daeed40089a708e52c25a1085 to your computer and use it in GitHub Desktop.
Simple JSON API Ruby Client
require 'net/http'
require 'json'
class Client
def call(method, url, path=nil, headers={}, body=nil, timeout=60)
net_class = Object.const_get("Net::HTTP::#{constantize(method)}")
uri = URI("#{url}#{path}")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', read_timeout: timeout) do |http|
request = net_class.new uri.request_uri
headers.each { |header, value| request[header] = value }
request.body = body.to_json if body
request.content_type = 'application/json;charset=UTF-8'
http.request request
end
json_body = JSON.parse(response.body) if response.body
return response.code, json_body
end
def constantize(str)
str.to_s.split('_').collect(&:capitalize).join
end
end
# usage
client = Client.new
http_code, json_body = client.call(:get, 'https://example.com')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment