Last active
December 13, 2018 15:04
-
-
Save ostinelli/e3e5d00daeed40089a708e52c25a1085 to your computer and use it in GitHub Desktop.
Simple JSON API Ruby Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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