Module: Enviso::API

Defined in:
lib/enviso/api.rb

Class Method Summary collapse

Class Method Details

.headersObject

HTTP headers to send in each request



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/enviso/api.rb', line 70

def headers
 h = {
    content_type: :json, 
    accept: :json, 
    cache_control: 'no-cache', 
    'x-api-key' => Enviso::Config.api_key, 
    'x-tenantsecretkey' => Enviso::Config.tenant_key
  }
  if Enviso::Authentication.auth_token
    h["Authorization"] = "bearer #{Enviso::Authentication.auth_token}"
  end
  return h
end

.send_request(type: :get, endpoint: String, body: nil, token: nil) ⇒ Object

Sends a request to the Enviso API and returns the parsed results



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
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
# File 'lib/enviso/api.rb', line 12

def send_request(type: :get, endpoint: String, body: nil, token: nil)
  url = "#{Enviso::Config.api_link}v#{Enviso::Config.api_version}/#{endpoint}"
  begin
    
    # Get a new API token is the current one has expired.
    unless Enviso::Authentication.has_valid_api_key || endpoint.include?("apis")
      Enviso::Authentication.get_new_token
    end

    if Enviso::Config.verbose
      puts "[ENVISO] Sending #{type.upcase} request to #{url}"
      puts "[ENVISO] Body:\n#{body}" if body
    end
    
    if type.to_sym == :post
      begin
        result = RestClient.post url, body.to_json, headers
      rescue RestClient::Unauthorized, RestClient::Forbidden => err
        raise "Access denied. API Response:\n#{err.response}"
      end
    elsif type.to_sym == :put
      begin
        result = RestClient.put url, body.to_json, headers
      rescue RestClient::Unauthorized, RestClient::Forbidden => err
        raise "Access denied. API Response:\n#{err.response}"
      end
    elsif type.to_sym == :delete
      begin
        # result = RestClient.delete url, headers
        result = RestClient::Request.execute(
          method: :delete, 
          url: url,
          body: body,
          headers: headers)
      rescue RestClient::Unauthorized, RestClient::Forbidden => err
        raise "Access denied. API Response:\n#{err.response}"
      end
    elsif type.to_sym == :get
      begin
        result = RestClient.get url, headers
      rescue RestClient::Unauthorized, RestClient::Forbidden => err
        raise "Access denied. API Response:\n#{err.response}"
      end
    end

    puts "[ENVISO] Result:\n#{result}" if Enviso::Config.verbose
    begin
      return JSON.parse(result)
    rescue
      return result
    end
  rescue RestClient::BadRequest => err
    raise "Bad Request. API Response:\n#{err.response}"
  end
end