Module: Xhash::JsonApi::ClassMethods
- Defined in:
- lib/xhash/client/json_api.rb
Instance Method Summary collapse
- #api_get(url:, headers: {}) ⇒ Object
- #api_post(url:, body: {}, headers: {}) ⇒ Object
- #api_post_multipart(url:, body: {}, headers: {}) ⇒ Object
- #default_headers ⇒ Object
- #response_ok?(response) ⇒ Boolean
Instance Method Details
#api_get(url:, headers: {}) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/xhash/client/json_api.rb', line 12 def api_get(url:, headers: {}) custom_headers = headers.merge(default_headers) response = HTTParty.get(Xhash.api_base + url, headers: custom_headers, timeout: Xhash.timeout) raise Xhash::Error.new(response) unless response_ok?(response) begin JSON.parse(response.body, symbolize_names: true) rescue => exception raise Xhash::MalformedResponse.new end end |
#api_post(url:, body: {}, headers: {}) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/xhash/client/json_api.rb', line 25 def api_post(url:, body: {}, headers: {}) custom_headers = headers.merge(default_headers) response = HTTParty.post( Xhash.api_base + url, body: body.to_json, headers: custom_headers, timeout: Xhash.timeout ) raise Xhash::Error.new(response) unless response_ok?(response) begin JSON.parse(response.body, symbolize_names: true) rescue => exception raise Xhash::MalformedResponse.new end end |
#api_post_multipart(url:, body: {}, headers: {}) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/xhash/client/json_api.rb', line 43 def api_post_multipart(url:, body: {}, headers: {}) custom_headers = headers.merge(default_headers) response = HTTParty.post( Xhash.api_base + url, multipart: true, body: body, headers: custom_headers, timeout: Xhash.timeout ) raise Xhash::Error.new(response) unless response_ok?(response) response.body end |
#default_headers ⇒ Object
6 7 8 9 10 |
# File 'lib/xhash/client/json_api.rb', line 6 def default_headers { 'Content-type' => 'application/json', 'Authorization' => Xhash.api_key } end |
#response_ok?(response) ⇒ Boolean
56 57 58 |
# File 'lib/xhash/client/json_api.rb', line 56 def response_ok?(response) !(response.code == 404 || response.code >= 500) end |