Make the call to the API server
975944
private function call($url)
        {
        $handle = curl_init();

        // set the options
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_ENCODING, "");
        curl_setopt($handle, CURLOPT_MAXREDIRS, 10);
        curl_setopt($handle, CURLOPT_TIMEOUT, 30);
        curl_setopt($handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");

        // make the call
        $output = curl_exec($handle);
        if ($output == false)
            {
            $this->error["code"]    = "BadConnection";
            $this->error["message"] = curl_error($handle);
            }

        curl_close($handle);

        // return the json
        return $output;
        }
881868
def call(self, func, *api_args, **api_kwargs):
        """"""
        if not isinstance(func, str) or (func == ''):
            msg = ('Invalid input for API name, should be a'
                   'string, type: %s specified.') % type(func)
            return self._construct_api_name_error(msg)

        # Create client socket
        try:
            cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as err:
            return self._construct_socket_error(1, error=six.text_type(err))

        try:
            # Set socket timeout
            cs.settimeout(self.timeout)
            # Connect SDK server
            try:
                cs.connect((self.addr, self.port))
            except socket.error as err:
                return self._construct_socket_error(2, addr=self.addr,
                                                    port=self.port,
                                                    error=six.text_type(err))

            # Prepare the data to be sent and switch to bytes if needed
            api_data = json.dumps((func, api_args, api_kwargs))
            api_data = api_data.encode()

            # Send the API call data to SDK server
            sent = 0
            total_len = len(api_data)
            got_error = False
            try:
                while (sent < total_len):
                    this_sent = cs.send(api_data[sent:])
                    if this_sent == 0:
                        got_error = True
                        break
                    sent += this_sent
            except socket.error as err:
                return self._construct_socket_error(5,
                                                    error=six.text_type(err))

            if got_error or sent != total_len:
                return self._construct_socket_error(3, sent=sent,
                                                    api=api_data)

            # Receive data from server
            return_blocks = []
            try:
                while True:
                    block = cs.recv(4096)
                    if not block:
                        break
                    block = bytes.decode(block)
                    return_blocks.append(block)
            except socket.error as err:
                # When the sdkserver cann't handle all the client request,
                # some client request would be rejected.
                # Under this case, the client socket can successfully
                # connect/send, but would get exception in recv with error:
                # "error: [Errno 104] Connection reset by peer"
                return self._construct_socket_error(6,
                                                    error=six.text_type(err))
        finally:
            # Always close the client socket to avoid too many hanging
            # socket left.
            cs.close()

        # Transform the received stream to standard result form
        # This client assumes that the server would return result in
        # the standard result form, so client just return the received
        # data
        if return_blocks:
            results = json.loads(''.join(return_blocks))
        else:
            results = self._construct_socket_error(4)
        return results
507711
function API(opts) {
  opts = opts || {};

  this.verbose = !!opts.verbose;
  this.request = opts.request || request;
  this.baseUrl = opts.baseUrl || BASE_URL;
  var parsedUrl = url.parse(this.baseUrl);
  this.basePath = parsedUrl.path;
  this.baseHost = parsedUrl.protocol + '//' + parsedUrl.host;
  this.timeout = opts.timeout || 50000;

  if (this.verbose) {
    log.setLevel('debug');
  } else {
    log.setLevel('info');
  }
}
383716
function runCall(name, call, input) {
    return web.post(connectorsUrl + '/' + name + '/' + call, input);
}
229093
function serviceCall(req, res, next) {
        connector.runCall(req.params.connection, req.params.call, req.body).then(res.json.bind(res), next).done();
    }
958179
def call(function, params)
      start
      req = Net::HTTP::Post.new(DEFAULT_PATH)
      req.add_field('Content-Type', 'application/json; charset=utf-8')
      req.body = URI::encode({
        :jsonrpc => :'2.0',
        :method => function,
        :params => params,
        :id => 0 }.to_json({:ascii_only => true}))
      begin
        res = @conn.request(req)
        if res.is_a?(Net::HTTPSuccess)
          data = res.body
          return JSON.parse(data)['result']
        else
          raise ConnectionError.new(res)
        end
      rescue ConnectionError => error
        raise error
      rescue Exception => error
        raise ConnectionError.new(error)
      end
    end
1333871
def api_request(*args, **kwargs):
        
        r = requests.request(*args, **kwargs)
        return APIResponse(r)
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)
301459
function callApi (method) {
  return function (req, res) {
    var apiAction = api[method](req.guid, req.options)
    handleResponse(apiAction, res)
  }
}
567070
def call_api_tsv(http_method, path, opts = {})
      request = build_request(http_method, path, opts)
      response = request.run

      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.timed_out?
          fail ApiError.new('Connection timed out')
        elsif response.code == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.return_message)
        else
          fail ApiError.new(:code => response.code,
                            :response_headers => response.headers,
                            :response_body => response.body),
               response.status_message
        end
      end

      if opts[:return_type]
        return_type = Pollster.const_get(opts[:return_type])
        data = return_type.from_tsv(response.body)
      else
        data = nil
      end
      return data, response.code, response.headers
    end
1165432
async def _call(self, params):
        """"""
        if self._session.closed:
            raise SabnzbdApiException('Session already closed')

        p = {**self._default_params, **params}
        try:
            async with timeout(self._timeout, loop=self._session.loop):
                async with self._session.get(self._api_url, params=p) as resp:
                    data = await resp.json()
                    if data.get('status', True) is False:
                        self._handle_error(data, params)
                    else:
                        return data
        except aiohttp.ClientError:
            raise SabnzbdApiException('Unable to communicate with Sabnzbd API')
        except asyncio.TimeoutError:
            raise SabnzbdApiException('SABnzbd API request timed out')
656176
def call(self, my_args=None):
        
        LOGGER.debug("rabbitmq.Requester.call")
        if my_args is None:
            raise exceptions.ArianeConfError("requestor call arguments")
        if 'properties' not in my_args or my_args['properties'] is None:
            raise exceptions.ArianeConfError('requestor call properties')
        if 'body' not in my_args or my_args['body'] is None:
            my_args['body'] = ''
        if 'MSG_CORRELATION_ID' not in my_args['properties']:
            self.corr_id = str(uuid.uuid4())
            my_args['properties']['MSG_CORRELATION_ID'] = self.corr_id
        else:
            self.corr_id = my_args['properties']['MSG_CORRELATION_ID']

        self.response = None
        self.corr_id = str(uuid.uuid4())

        props = my_args['properties']
        if 'sessionID' in props and props['sessionID'] is not None and props['sessionID']:
            request_q = str(props['sessionID']) + '-' + self.requestQ
        else:
            request_q = self.requestQ

        if self.trace:
            props['MSG_TRACE'] = True

        if not self.fire_and_forget:
            properties = pika.BasicProperties(content_type=None, content_encoding=None,
                                              headers=props, delivery_mode=None,
                                              priority=None, correlation_id=self.corr_id,
                                              reply_to=self.callback_queue, expiration=None,
                                              message_id=None, timestamp=None,
                                              type=None, user_id=None,
                                              app_id=None, cluster_id=None)
        else:
            properties = pika.BasicProperties(content_type=None, content_encoding=None,
                                              headers=props, delivery_mode=None,
                                              priority=None, expiration=None,
                                              message_id=None, timestamp=None,
                                              type=None, user_id=None,
                                              app_id=None, cluster_id=None)

        self.channel.basic_publish(exchange='',
                                   routing_key=request_q,
                                   properties=properties,
                                   body=str(my_args['body']))

        LOGGER.debug("rabbitmq.Requester.call - published msg {"+str(my_args['body'])+","+str(properties)+"}")

        if not self.fire_and_forget:
            start_time = timeit.default_timer()
            timeout = self.rpc_timeout if self.rpc_timeout > 0 else 0
            while self.response is None and timeout >= 0:
                timeout_id = None
                if timeout > 0:
                    timeout_id = self.connection.add_timeout(timeout, self.on_response)
                self.connection.process_data_events()
                if timeout_id is not None:
                    self.connection.remove_timeout(timeout_id)
                timeout = round(self.rpc_timeout - (timeit.default_timer() - start_time))
            rpc_time = timeit.default_timer() - start_time

            if self.response is None:
                if self.rpc_retry > 0:
                    if 'retry_count' not in my_args:
                        my_args['retry_count'] = 1
                        LOGGER.debug("rabbitmq.Requester.call - Retry (" + str(my_args['retry_count']) + ")")
                        return self.call(my_args)
                    elif 'retry_count' in my_args and (self.rpc_retry - my_args['retry_count']) > 0:
                        LOGGER.warn("rabbitmq.Requester.call - No response returned from request on " + request_q +
                                    " queue after " + str(self.rpc_timeout) + '*' +
                                    str(self.rpc_retry) + " sec ...")
                        self.trace = True
                        my_args['retry_count'] += 1
                        LOGGER.warn("rabbitmq.Requester.call - Retry (" + str(my_args['retry_count']) + ")")
                        return self.call(my_args)
                    else:
                        raise ArianeMessagingTimeoutError('rabbitmq.Requester.call',
                                                          'Request timeout (' + str(self.rpc_timeout) + '*' +
                                                          str(self.rpc_retry) + ' sec) occured')
                else:
                    raise ArianeMessagingTimeoutError('rabbitmq.Requester.call',
                                                      'Request timeout (' + str(self.rpc_timeout) + '*' +
                                                      str(self.rpc_retry) + ' sec) occured')
            else:
                if self.rpc_timeout > 0 and rpc_time > self.rpc_timeout*3/5:
                    LOGGER.debug('rabbitmq.Requester.call - slow RPC time (' + str(rpc_time) + ') on request ' +
                                 str(properties))
                self.trace = False

                rc_ = self.response['props'].headers['RC']
                if rc_ != 0:
                    try:
                        content = json.loads(self.response['body'].decode("UTF-8"))
                    except ValueError:
                        content = self.response['body'].decode("UTF-8")
                    return DriverResponse(
                        rc=rc_,
                        error_message=self.response['props'].headers['SERVER_ERROR_MESSAGE']
                        if 'SERVER_ERROR_MESSAGE' in self.response['props'].headers else '',
                        response_content=content
                    )
                else:
                    try:
                        if 'MSG_PROPERTIES' in self.response['props'].headers:
                            props = json.loads(self.response['props'].headers['MSG_PROPERTIES'])
                        else:
                            props = None
                    except ValueError:
                        if 'MSG_PROPERTIES' in self.response['props'].headers:
                            props = self.response['props'].headers['MSG_PROPERTIES']
                        else:
                            props = None
                    try:
                        content = json.loads(self.response['body'].decode("UTF-8"))
                    except ValueError:
                        content = self.response['body'].decode("UTF-8")
                    return DriverResponse(
                        rc=rc_,
                        response_properties=props,
                        response_content=content
                    )
1199495
protected function call()
    {
        // Check if the curl object is set
        if (!$this->isInit()) {
            // If it isn't, we do it right now
            $this->init();
        }

        $options = array();
        // Set basic authentication if enabled
        if ($this->authentication instanceof BasicAuthentication) {
            $options['auth'] = array(
                $this->authentication->getUsername(),
                $this->authentication->getPassword()
            );
        }

        $request = $this->getHttpClient()->createRequest(
            $this->getHttpMethod(),
            $this->getEndpoint(),
            array_merge(
                $options,
                array('headers' => $this->getHeaders())
            )
        );

        foreach ($this->getEndpointParameters() as $key => $value) {
            $request->getQuery()->set($key, $value);
        }

        if (($body = $this->getBody()) !== null) {
            $request->setBody(\GuzzleHttp\Stream\Stream::factory($body));
        }

        try {
            $response = $this->getHttpClient()->send($request);
        } catch (ClientException $e) {// Check if not found
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_NOT_FOUND) {
                throw new HttpNotFoundException();
            }

            // Check if unauthorized
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_UNAUTHORIZED) {
                throw new UnauthorizedException();
            }

            throw $e;
        }

        $this->setHttpStatusCode($response->getStatusCode());

        if ($this->getAccept() == 'application/json') {
            $this->setData($response->json());
        } else {
            $this->setData($response->getBody(true));
        }
    }
1079268
def call(args = {}, &block)
      response = API.call(full_name, args, token)
      Result.process(response, type, block)
    end
149059
def callm(method, param_dict, POST=False, socket_timeout=None, data=None):
    
    try:
        param_dict['api_key'] = config.ECHO_NEST_API_KEY
        param_list = []
        if not socket_timeout:
            socket_timeout = config.CALL_TIMEOUT

        for key,val in param_dict.iteritems():
            if isinstance(val, list):
                param_list.extend( [(key,subval) for subval in val] )
            elif val is not None:
                if isinstance(val, unicode):
                    val = val.encode('utf-8')
                param_list.append( (key,val) )

        params = urllib.urlencode(param_list)

        orig_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(socket_timeout)

        if(POST):
            if (not method == 'track/upload') or ((method == 'track/upload') and 'url' in param_dict):
                """
                this is a normal POST call
                """
                url = 'http://%s/%s/%s/%s' % (config.API_HOST, config.API_SELECTOR,
                                            config.API_VERSION, method)

                if data is None:
                    data = ''
                data = urllib.urlencode(data)
                data = "&".join([data, params])

                f = opener.open(url, data=data)
            else:
                """
                upload with a local file is special, as the body of the request is the content of the file,
                and the other parameters stay on the URL
                """
                url = '/%s/%s/%s?%s' % (config.API_SELECTOR, config.API_VERSION,
                                            method, params)

                if ':' in config.API_HOST:
                    host, port = config.API_HOST.split(':')
                else:
                    host = config.API_HOST
                    port = 80

                if config.TRACE_API_CALLS:
                    logger.info("%s/%s" % (host+':'+str(port), url,))
                conn = httplib.HTTPConnection(host, port = port)
                conn.request('POST', url, body = data, headers = dict([('Content-Type', 'application/octet-stream')]+headers))
                f = conn.getresponse()

        else:
            """
            just a normal GET call
            """
            url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION,
                                            method, params)

            f = opener.open(url)

        socket.setdefaulttimeout(orig_timeout)

        # try/except
        response_dict = get_successful_response(f)
        return response_dict

    except IOError, e:
        if hasattr(e, 'reason'):
            raise EchoNestIOError(error=e.reason)
        elif hasattr(e, 'code'):
            raise EchoNestIOError(code=e.code)
        else:
            raise
1259231
public function call() {
    if (empty($this->getApp()->getRequest()->apiApplication)) {
      $this->getApp()->returnError(DefaultAppErrors::$NOT_AUTHORIZED);
    }

    if (!empty($this->next)) {
      $this->next->call();
    }
  }
543198
def call(req, args={}, &block)
      oauth_args = args.delete(:oauth) || {}
      http_response = @oauth_consumer.post_form(REST_PATH, @access_secret, {:oauth_token => @access_token}.merge(oauth_args), build_args(args, req))
      process_response(req, http_response.body)
    end