Method: Monkeylearn::Requests#request

Defined in:
lib/monkeylearn/requests.rb

#request(method, path, data = nil, query_params = nil) ⇒ Object



8
9
10
11
12
13
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
# File 'lib/monkeylearn/requests.rb', line 8

def request(method, path, data = nil, query_params = nil)
  unless Monkeylearn.token
    raise MonkeylearnError, 'Please initialize the Monkeylearn library with your API token'
  end

  while true
    response = get_connection.send(method) do |req|
      url = path.to_s
      if query_params
        url += '?' + URI.encode_www_form(query_params)
      end
      req.url url
      req.headers['Authorization'] = 'Token ' + Monkeylearn.token
      req.headers['Content-Type'] = 'application/json'
      req.headers['User-Agent'] = 'ruby-sdk'
      if data
        req.body = data.to_json
      end
    end

    seconds = throttled?(response)
    if seconds && Monkeylearn.retry_if_throttle
      sleep seconds
    else
      break
    end
  end

  if response.status != 200
    raise_for_status(response)
  end

  Monkeylearn::Response.new(response)
end