module Enviso::API

Public Class Methods

headers() click to toggle source

HTTP headers to send in each request

# 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) click to toggle source

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

# 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