Module: Decathlon::HTTPS
- Defined in:
- lib/decathlon/https.rb
Overview
Cleanly handles HTTPS requests to JSON apis
Constant Summary collapse
- VERSION =
'0.1.2'
Class Method Summary collapse
Class Method Details
.json_api_request(base_url: '', params: {}, verb: :get, headers: {}, return_http_status_code: false) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/decathlon/https.rb', line 14 def self.json_api_request(base_url: '', params: {}, verb: :get, headers: {}, return_http_status_code: false) # Parse URI and build a new HTTPS client # uri = URI.parse(base_url) raise 'InsecureRequestURL' unless uri.scheme == 'https' http = ::Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER # Don't include empty params # params = params.reject{ |_k, v| v.nil? } # Use the HTTP verb to create a request and set params # case verb when :get uri.query = params.collect{ |k, v| "#{k}=#{v}" }.join('&') request = ::Net::HTTP::Get.new(uri.request_uri) when :delete uri.query = params.collect{ |k, v| "#{k}=#{v}" }.join('&') request = ::Net::HTTP::Delete.new(uri.request_uri) when :post request = ::Net::HTTP::Post.new(uri.request_uri) request.body = JSON.dump(params) when :put request = ::Net::HTTP::Put.new(uri.request_uri) request.body = JSON.dump(params) when :patch request = ::Net::HTTP::Patch.new(uri.request_uri) request.body = JSON.dump(params) else raise 'Invalid HTTP verb' end # Add headers to the request # headers.each do |k, v| request[k.to_s] = v end # Ensure request is JSON # request['Content-Type'] = 'application/json' # Make an HTTPS query to the host and return a symbolized hash of the JSON response # response = http.request(request) code = response.code.to_i body = response.body.to_s # Return parsed body content, and status code if requested # return { body: JSON.parse(body, symbolize_names: true), code: code } if return_http_status_code == true return {} if code == 204 || (body.empty? && code < 400) return JSON.parse(body, symbolize_names: true) end |