Class: Kitties::Client
- Inherits:
-
Object
- Object
- Kitties::Client
- Defined in:
- lib/kittyverse/api/client.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#get(service, **params) ⇒ Object
method initialize.
-
#initialize(base_uri:, token: nil) ⇒ Client
constructor
todo: add (optional) close with @http.close - why? why not?.
Constructor Details
#initialize(base_uri:, token: nil) ⇒ Client
todo: add (optional) close with @http.close - why? why not?
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/kittyverse/api/client.rb', line 70 def initialize( base_uri:, token: nil ) uri = URI.parse( base_uri ) @http = Net::HTTP.new( uri.host, uri.port ) if uri.instance_of? URI::HTTPS @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end @base_request_uri = uri.request_uri ## e.g. save /v1 etc. ## puts "base_request_uri: >#{@base_request_uri}<" @request_headers = if token { "x-api-token" => token } else {} end end |
Instance Method Details
#get(service, **params) ⇒ Object
method initialize
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/kittyverse/api/client.rb', line 88 def get( service, **params ) ## add url-encoded query string from params hash e.g. ?limit=100&type=sale unless params.empty? query = URI.encode_www_form( params ) service += "?#{query}" end puts "GET #{service}" request_uri = if @base_request_uri == "/" service else "#{@base_request_uri}#{service}" ## e.g. add /v1 etc. end pp @request_headers req = Net::HTTP::Get.new( request_uri, @request_headers ) res = @http.request(req) headers = res.to_hash ## get all response headers if Kitties.debug? # Iterate all response headers. # res.each_header do |key, value| # p "#{key} => #{value}" # end pp headers # => "content-type => application/json; charset=utf-8" # => "x-ratelimit-limit => 20" # => "x-ratelimit-remaining => 19" # => "x-ratelimit-reset => 1558079593" # ... end body = res.read_body ## pp body ## track last response Kitties.last_response = Response.new( res.code, res., headers, body ) if res.code != '200' raise HttpError.new( res.code, res. ) end json = JSON.parse( body ) ## use just body (any difference?) - why? why not? ## pp json json end |