Last active
March 22, 2016 04:01
-
-
Save stevenschobert/8df1dc08a96ba0ecc274 to your computer and use it in GitHub Desktop.
Quick start file for an API client in Ruby
This file contains hidden or 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
| class ApiClient | |
| attr_accessor :api_key | |
| def initialize(api_key: nil) | |
| @api_key = api_key | |
| end | |
| def some_method | |
| path = "/some_path" | |
| get_json!(path) | |
| end | |
| private | |
| def authorize_request(request) | |
| request["Authorization"] = "Bearer #{ api_key }" | |
| end | |
| def base_uri | |
| @base_uri ||= URI("https://apiurl.com") | |
| end | |
| def get_json!(path) | |
| request = Net::HTTP::Get.new(path) | |
| response_json(run_request!(request)) | |
| end | |
| def http | |
| @http ||= begin | |
| http = Net::HTTP.new(base_uri.host, base_uri.port) | |
| if base_uri.scheme == "https" | |
| http.use_ssl = true | |
| end | |
| http | |
| end | |
| end | |
| def json_headers | |
| @json_headers ||= { "Content-Type" => "application/json" } | |
| end | |
| def post_json!(path, body = {}, headers = {}) | |
| request = Net::HTTP::Post.new(path) | |
| json_headers.merge(headers).each{ |k,v| request[k] = v } | |
| request.body = body.to_json | |
| response_json(run_request!(request)) | |
| end | |
| def response_json(response) | |
| JSON.parse(response.body) | |
| rescue | |
| nil | |
| end | |
| def run_request(request) | |
| authorize_request(request) | |
| http.request(request) | |
| end | |
| def run_request!(request) | |
| response = run_request(request, target: target) | |
| unless response.kind_of?(Net::HTTPSuccess) | |
| raise "Got #{ response.code } for request: #{ request.path }: #{ response.body }" | |
| end | |
| response | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment