a helper method for relaying requests from client to api
559772
def _requests(self, url, method='GET', headers=None, params=None, data=None, errors=None):

        '''  '''

        title = '%s._requests' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # validate access token
        if not self._access_token:
            self.access_token()
            if self.retrieve_details:
                self._get_products()
    
    # refresh token
        current_time = time()
        if current_time > self.expires_at:
            self.access_token()
            if self.retrieve_details:
                self._get_products()

    # construct request kwargs
        request_kwargs = {
            'url': url,
            'headers': { 
                'Authorization': 'Bearer %s' % self._access_token,
                'Accept': 'application/json;v=2'
            },
            'params': {},
            'data': {}
        }
        if headers:
            request_kwargs['headers'].update(headers)
        if params:
            request_kwargs['params'].update(params)
        if data:
            request_kwargs['data'].update(data)

    # send request
        if method == 'POST':
            try:
                response = requests.post(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'POST'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        elif method == 'GET':
            try:
                response = requests.get(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'GET'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        else:
            raise ValueError('%s(method='') must be either GET or POST' % title)

    # handle response
        response_details = self.response_handler.handle(response, errors)
        
        return response_details
1308861
async def request(
            self,
            method: str,
            endpoint: str,
            *,
            base_url: str = API_URL_SCAFFOLD,
            headers: dict = None,
            params: dict = None,
            json: dict = None) -> dict:
        """"""
        if not headers:
            headers = {}
        headers.update({'Content-Type': 'application/json'})

        if not params:
            params = {}

        if self._api_key:
            params.update({'key': self._api_key})

        url = '{0}/{1}'.format(base_url, endpoint)
        async with self.websession.request(method, url, headers=headers,
                                           params=params, json=json) as resp:
            data = await resp.json(content_type=None)
            _raise_on_error(data)
            return data
735103
def request(req=None, method=None, requires_response=True):
    """"""
    if req is None:
        return functools.partial(request, method=method,
                                 requires_response=requires_response)

    @functools.wraps(req)
    def wrapper(self, *args, **kwargs):
        if self.lsp_ready:
            params = req(self, *args, **kwargs)
            if params is not None:
                self.emit_request(method, params, requires_response)
    return wrapper
832408
function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
117557
function Request(req, res, url) {
  if (!(this instanceof Request))
    return new Request(req, res, url);

  EventEmitter.call(this);

  this.req = null;
  this.res = null;
  this.socket = null;
  this.method = 'GET';
  this.headers = Object.create(null);
  this.contentType = 'bin';
  this.url = '/';
  this.pathname = '/';
  this.path = [];
  this.trailing = false;
  this.query = Object.create(null);
  this.params = Object.create(null);
  this.body = Object.create(null);
  this.hasBody = false;
  this.username = null;
  this.readable = true;
  this.writable = false;

  if (req)
    this.init(req, res, url);
}
658447
function Requester() {
		// setup abstract layer
		core.RequesterAbstract.apply(this, arguments);

		// parse the argument
		if (typeof this.object === 'number' || typeof this.object === 'string') {
			this.object = net.createConnection(this.object);
		} else if (!(this.object instanceof net.Server)) {
			this.object = net.createConnection(this.object.port, this.object.host);
		}

		// relay errors
		this.object.on('error', this.emit.bind(this, 'error'));

		// when socket is closed we will emit the close event
		this.object.on('close', this.emit.bind(this, 'close'));

		// setup a json stream handler there rescive data from the TCP socket
		jsonStream(this, this.object);
	}
489827
function request(url, options, callback)
{
  var connection;

  if (typeof options == 'function')
  {
    callback = options;
    options  = {};
  }

  connection = hyperquest(url, options, once(function(error, response)
  {
    if (error)
    {
      callback(error, response);
      return;
    }

    // set body
    response.body = '';

    // accumulate response body
    response.on('data', function(data)
    {
      response.body += data.toString();
    });

    response.on('end', function()
    {
      callback(null, response);
    });
  }));

  return connection;
}
869177
function(options,done) {

    request(options, function (err, response, payload) {
        if (err) {
            console.log('api call error');
            console.log(err);
        }

        done(err, payload, parseRateLimits(response.headers));
    });
}
505763
def request(self, api_commands, *, timeout=None):
        """"""
        if not isinstance(api_commands, list):
            return self._execute(api_commands, timeout=timeout)

        command_results = []

        for api_command in api_commands:
            result = self._execute(api_command, timeout=timeout)
            command_results.append(result)

        return command_results
421664
function intercept(req, res, next) {
    if (
         !route.test(req.url)           // Incorrect URL.
      || !req.headers.authorization     // Missing authorization.
      || options.method !== req.method  // Invalid method.
    ) return next();

    //
    // Handle unauthorized requests.
    //
    if (authorization !== req.headers.authorization) {
      res.statusCode = 401;
      res.setHeader('Content-Type', 'application/json');

      return res.end(JSON.stringify({
        ok: false,
        reason: [
          'I am programmed to protect, and sacrifice if necessary.',
          'Feel the power of my lazers! Pew pew!'
        ].join(' ')
      }));
    }

    var primus = this
      , buff = '';

    if (typeof options.middleware === 'function') {
      options.middleware(primus, parse, req, res, next);
    } else {
      //
      // Receive the data from the socket. The `setEncoding` ensures that Unicode
      // chars are correctly buffered and parsed before the `data` event is
      // emitted.
      //
      req.setEncoding('utf8');
      req.on('data', function data(chunk) {
        buff += chunk;
      }).once('end', function end() {
        parse(primus, buff, res);
      });
    }
  }
413484
function Requester() {
		// setup abstract layer
		core.RequesterAbstract.apply(this, arguments);

		// in case the process die, the connection will be severed
		this.object.on('exit', function () {
			if (self.online === true) {
				this.emit('close');
			}
		});

		// just relay message object they do not need to be parsed
		this.object.on('message', this.emit.bind(this, 'message'));

		// when the remote request a method, the methods should exists in .handlers
		var self = this;
		this.handlers.close = function () {
			this.callback();
			self.emit('close');
		};
	}
794271
def _request(self, method, url, headers=None, params=None, **aio_kwargs):
        """"""
        access_token = params.pop(self.access_token_key, None)
        if access_token:
            headers['Authorization'] = "Bearer %s" % access_token
        return super(DiscordClient, self)._request(
            method, url, headers=headers, params=params, **aio_kwargs)
959334
function(apiKey) {
  return function(path, data, done) {
    var url = apiBase + path + '?' + querystring.stringify(_.extend({ 'key': apiKey }, data));
    request.get(url, globalResponseHandler({ url: url }, done));
  };
}
1245445
def requester(
        url,
        main_url=None,
        delay=0,
        cook=None,
        headers=None,
        timeout=10,
        host=None,
        proxies=[None],
        user_agents=[None],
        failed=None,
        processed=None
    ):
    """"""
    cook = cook or set()
    headers = headers or set()
    user_agents = user_agents or ['Photon']
    failed = failed or set()
    processed = processed or set()
    # Mark the URL as crawled
    processed.add(url)
    # Pause/sleep the program for specified time
    time.sleep(delay)

    def make_request(url):
        """Default request"""
        final_headers = headers or {
            'Host': host,
            # Selecting a random user-agent
            'User-Agent': random.choice(user_agents),
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip',
            'DNT': '1',
            'Connection': 'close',
        }
        try:
            response = SESSION.get(
                url,
                cookies=cook,
                headers=final_headers,
                verify=False,
                timeout=timeout,
                stream=True,
                proxies=random.choice(proxies)
            )
        except TooManyRedirects:
            return 'dummy'

        if 'text/html' in response.headers['content-type'] or \
           'text/plain' in response.headers['content-type']:
            if response.status_code != '404':
                return response.text
            else:
                response.close()
                failed.add(url)
                return 'dummy'
        else:
            response.close()
            return 'dummy'

    return make_request(url)
27383
def request(self, url, method, data=None, headers=None):
        
        http_headers = merge_dict(self.default_headers, headers or {})
        request_data = merge_dict({'api_key': self.apikey}, data or {})

        logger.info('HTTP %s REQUEST TO %s' % (method, url))

        start = datetime.datetime.now()

        try:
            response = requests.request(method=method, url=url, data=json.dumps(request_data),
                                        headers=http_headers)
        except exceptions.BadRequestError as e:
            return json.loads({'errors': e.content})

        duration = datetime.datetime.now() - start

        logger.info('RESPONSE %s DURATION %s.%s' % (response.encoding, duration.seconds,
                                                    duration.microseconds))

        return json.loads(response.content) if response.content else {}
1369465
def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False):
        """"""
        method = method.lower()
        params = params or {}

        func = getattr(self.client, method)
        if isinstance(params, dict) and json_encoded is False:
            params, files = _transparent_params(params)
        else:
            params = params
            files = list()

        requests_args = {}
        for k, v in self.client_args.items():
            # Maybe this should be set as a class variable and only done once?
            if k in ('timeout', 'allow_redirects', 'stream', 'verify'):
                requests_args[k] = v

        if method == 'get' or method == 'delete':
            requests_args['params'] = params
        else:
            # Check for json_encoded so we will sent params as "data" or "json"
            if json_encoded:
                data_key = 'json'
            else:
                data_key = 'data'
            requests_args.update({
                data_key: params,
                'files': files,
            })
        try:
            response = func(url, **requests_args)
        except requests.RequestException as e:
            raise TwythonError(str(e))

        # create stash for last function intel
        self._last_call = {
            'api_call': api_call,
            'api_error': None,
            'cookies': response.cookies,
            'headers': response.headers,
            'status_code': response.status_code,
            'url': response.url,
            'content': response.text,
        }

        # greater than 304 (not modified) is an error
        if response.status_code > 304:
            error_message = self._get_error_message(response)
            self._last_call['api_error'] = error_message

            ExceptionType = TwythonError
            if response.status_code == 429:
                # Twitter API 1.1, always return 429 when
                # rate limit is exceeded
                ExceptionType = TwythonRateLimitError
            elif response.status_code == 401 or 'Bad Authentication data' \
                    in error_message:
                # Twitter API 1.1, returns a 401 Unauthorized or
                # a 400 "Bad Authentication data" for invalid/expired
                # app keys/user tokens
                ExceptionType = TwythonAuthError

            raise ExceptionType(
                error_message,
                error_code=response.status_code,
                retry_after=response.headers.get('X-Rate-Limit-Reset'))
        content = ''
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            if response.content != '':
                raise TwythonError('Response was not valid JSON. \
                                   Unable to decode.')

        return content