Call an API with given options.

 @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
   the data deserialized from response body (could be nil), response status code and response headers.
541358
def call_api(http_method, path, opts = {})
      response = build_request(http_method, path, opts)
      download_file response if opts[:return_type] == 'File'
      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.status == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.reason_phrase)
        else
          fail ApiError.new(:code => response.status,
                            :response_headers => response.headers,
                            :response_body => response.body),
               response.reason_phrase
        end
      end
      if opts[:return_type]
        data = deserialize(response, opts[:return_type])
      else
        data = nil
      end
      [data, response.status, response.headers]
    end
1253509
def _response(status, body=nil, headers={})
      body = [body].compact
      headers = headers.merge("Content-Type" => "application/json")
      Rack::Response.new(body, status, headers).finish
    end
363358
def call(self, operation, data):
        """"""
        print('API call [{0}:{1}], method - {2}, data - {3}'.format(
            self.host, self.api_key, operation, repr(data)))
165421
def _do_request(self, method, *args, **kwargs):
        
        log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
            args[0], kwargs.get('headers'), kwargs.get('json'), method,),
            level=logging.DEBUG,)
        requests_method = getattr(requests, method)
        return self._handle_response(requests_method(*args, **kwargs))
984987
def parse_response(resp)
      body = JSON.parse(resp.body)
      if body['error']
        raise Apilayer::Error.new(
          body['error']['info'],
          body['error']['code']
        )
      else
        body
      end
    end
777257
def call(call, access_token = false, params = {}, risk_token = false, client_ip = false)
      path = call.start_with?('/') ? call : call.prepend('/')
      url  = URI.parse(api_endpoint + path)

      call = Net::HTTP::Post.new(url.path, {
        'Content-Type' => 'application/json',
        'User-Agent'   => 'WePay Ruby SDK'
      })

      unless params.empty?
        call.body = params.to_json
      end

      if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end
      if @api_version then call.add_field('Api-Version', @api_version); end
      if risk_token then call.add_field('WePay-Risk-Token', risk_token); end
      if client_ip then call.add_field('Client-IP', client_ip); end

      make_request(call, url)
    end
121740
def request(opts = {})
      method = opts.delete(:_method)
      path = opts.delete(:_path)
      headers = opts.delete(:_headers)
      opts.delete_if { |key, _| key.to_s =~ /^_/ } # Remove all internal parameters
      if method == :options
        # Faraday doesn't support the OPTIONS verb because of a name collision with an internal options method
        # so we need to call run_request directly.
        request.headers.merge!(headers) if headers
        response = @connection.run_request method, path, opts, headers
      else
        response = @connection.send method do |request|
          request.headers.merge!(headers) if headers
          if method == :get
            # For GET requests, treat additional parameters as querystring data
            request.url path, opts
          else
            # For POST, PUT and DELETE requests, treat additional parameters as request body
            request.url path
            request.body = opts
          end
        end
      end
      { :parsed_data => response.env[:body], :response => response }
    end
233932
def call(payload=None):
    '''
    
    '''
    r = None
    try:
        if DETAILS['method'] == 'dev_key':
            # Pass the api key without the target declaration
            conditional_payload = {'key': DETAILS['apikey']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'dev_pass':
            # Pass credentials without the target declaration
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_key':
            # Pass the api key with the target declaration
            conditional_payload = {'key': DETAILS['apikey'],
                                   'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_pass':
            # Pass credentials with the target declaration
            conditional_payload = {'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
    except KeyError as err:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if not r:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if six.text_type(r['status']) not in ['200', '201', '204']:
        if six.text_type(r['status']) == '400':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request due to a client error.")
        elif six.text_type(r['status']) == '401':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request because it lacks valid authentication "
                "credentials for the target resource.")
        elif six.text_type(r['status']) == '403':
            raise salt.exceptions.CommandExecutionError(
                "The server refused to authorize the request.")
        elif six.text_type(r['status']) == '404':
            raise salt.exceptions.CommandExecutionError(
                "The requested resource could not be found.")
        else:
            raise salt.exceptions.CommandExecutionError(
                "Did not receive a valid response from host.")

    xmldata = ET.fromstring(r['text'])

    # If we are pulling the candidate configuration, we need to strip the dirtyId
    if payload['type'] == 'config' and payload['action'] == 'get':
        xmldata = (_strip_dirty(xmldata))

    return xml.to_dict(xmldata, True)
834530
def _api_query(self, protection=None, path_dict=None, options=None):
        

        if not options:
            options = {}

        if self.api_version not in path_dict:
            raise Exception('method call not available under API version {}'.format(self.api_version))

        request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1
        request_url = request_url.format(path=path_dict[self.api_version])

        nonce = str(int(time.time() * 1000))

        if protection != PROTECTION_PUB:
            request_url = "{0}apikey={1}&nonce={2}&".format(request_url, self.api_key, nonce)

        request_url += urlencode(options)

        try:
            if sys.version_info >= (3, 0) and protection != PROTECTION_PUB:

                apisign = hmac.new(bytearray(self.api_secret, 'ascii'),
                                   bytearray(request_url, 'ascii'),
                                   hashlib.sha512).hexdigest()

            else:

                apisign = hmac.new(self.api_secret.encode(),
                                   request_url.encode(),
                                   hashlib.sha512).hexdigest()

            self.wait()

            return self.dispatch(request_url, apisign)

        except Exception:
            return {
                'success': False,
                'message': 'NO_API_RESPONSE',
                'result': None
            }
659900
def _parse_api_options(self, options, query_string=False):
        
        api_options = self._select_options(options, self.API_OPTIONS)
        if query_string:
            # Prefix all options with "opt_"
            query_api_options = {}
            for key in api_options:
                # Transform list/tuples into comma separated list
                if isinstance(api_options[key], (list, tuple)):
                    query_api_options[
                        'opt_' + key] = ','.join(api_options[key])
                else:
                    query_api_options[
                        'opt_' + key] = api_options[key]
            return query_api_options
        else:
            return api_options
1173891
def call(object, method, *args, &block)
      options = args.last.is_a?(Hash) ? args.pop : {}
      options = {:method_name => method}.merge(options)
      state = machine.states.match!(object)

      if state == self && object.respond_to?(method)
        object.send(method, *args, &block)
      elsif method_missing = options[:method_missing]
        # Dispatch to the superclass since the object either isn't in this state
        # or this state doesn't handle the method
        begin
          method_missing.call
        rescue NoMethodError => ex
          if ex.name.to_s == options[:method_name].to_s && ex.args == args
            # No valid context for this method
            raise InvalidContext.new(object, "State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}")
          else
            raise
          end
        end
      end
    end
919365
def make_api_call(self, method, url, json_params=None):
        

        url = self.BRANCH_BASE_URI+url

        if self.verbose is True:
            print("Making web request: {}".format(url))

        if json_params is not None:
            encoded_params = json.dumps(json_params)
            headers = {'Content-Type': 'application/json'}
        else:
            encoded_params = None
            headers = {}

        if encoded_params is not None and self.verbose is True:
            print("Params: {}".format(encoded_params))

        request = Request(url, encoded_params.encode('utf-8'), headers)
        request.get_method = lambda: method
        response = urlopen(request).read()
        return json.loads(response.decode('utf-8'))
387218
def api_request(action, data, request_type, binary_key = nil)
      if !binary_key.nil?
        binary_key_data = data[binary_key]
        data.delete(binary_key)
      end

      if data[:format].nil? || data[:format] == 'json'
        data = prepare_json_payload(data)
      else
        data[:api_key] = @api_key
        data[:format] ||= 'json'
        data[:sig] = get_signature_hash(data, @secret)
      end

      if !binary_key.nil?
        data[binary_key] = binary_key_data
      end
      _result = http_request(action, data, request_type, binary_key)

      # NOTE: don't do the unserialize here
      if data[:format] == 'json'
        begin
          unserialized = JSON.parse(_result)
          return unserialized ? unserialized : _result
        rescue JSON::JSONError => e
          return {'error' => e}
        end
      end
      _result
    end
816871
def parse_dynamic_options
      if no_options_passed?
        {}
      else
        dynamic_parser.parse!(@params)

        data = dynamic_parser.to_hash
        invalid_key = data.find { |key, value| value.nil? }

        if invalid_key
          raise InvalidOptions.new(invalid_key.first)
        end

        data
      end
    end
1296068
def parse_options options = {}, request = ''
      options.each do |opt, value|
        case opt
        when :timeout, :paging, :mode
          request += "&#{opt}=#{value}"
        when :callback, :stats
          request += "&#{opt}"
        when :fields
          request += "&#{opt}=" + value.join(',') if value.is_a?(Array)
        end
      end
      request
    end
810675
def generate_snake_method_body(api, options, &def_block)
      if def_block
        if options[:fails]
          ->(*args, &block){ (res = def_block.(api, *args, &block)) == options[:fails] ? nil: res }
        elsif options[:boolean]
          ->(*args, &block){ def_block.(api, *args, &block) != 0 }
        else
          ->(*args, &block){ def_block.(api, *args, &block) }
        end
      else
        if options[:fails]
          ->(*args, &block){ (res = block ? block[api.call(*args)] : api.call(*args)) == options[:fails] ? nil : res }
        elsif options[:boolean]
          ->(*args, &block){ block ? block[api.call(*args)] : api.call(*args) != 0 }
        else
          ->(*args, &block){ block ? block[api.call(*args)] : api.call(*args) }
        end
      end
    end
669546
def call_api(self,
                 action,
                 params=None,
                 method=('API', 'POST', 'application/x-www-form-urlencoded'),
                 **kwargs):
        
        urltype, methodname, content_type = method
        if urltype == 'SMS':
            url = self.sms_host
        else:
            url = self.api_host
        if content_type == 'application/json':
            data = json.dumps(params)
        else:
            data = self._filter_params(params)
        return self._http_call(
            url=url + action,
            method=methodname,
            data=data,
            headers=self._headers(content_type),
            **kwargs)