General API Requests
965528
public function createSession($options)
    {
        $request = new Request('POST', '/session/create');
        try {
            $response = $this->client->send($request, [
                'debug' => $this->isDebug(),
                'form_params' => $this->postFieldsForOptions($options)
            ]);
            $sessionXml = $this->getResponseXml($response);
        } catch (\RuntimeException $e) {
            // TODO: test if we have a parse exception and handle it, otherwise throw again
            throw $e;
        } catch (\Exception $e) {
            $this->handleException($e);
            return;
        }
        return $sessionXml;
    }
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);
}
658520
def request_show(self, id, **kwargs):
        ""
        api_path = "/api/v2/requests/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
848319
def _request(self, method, uri_relative, request_bytes, params,
                 custom_headers):
        

        uri_relative_with_params = self._append_params_to_uri(uri_relative,
                                                              params)
        if uri_relative not in self._URIS_NOT_REQUIRING_ACTIVE_SESSION:
            if self._api_context.ensure_session_active():
                from bunq.sdk.context import BunqContext

                BunqContext.update_api_context(self._api_context)

        all_headers = self._get_all_headers(
            method,
            uri_relative_with_params,
            request_bytes,
            custom_headers
        )

        response = requests.request(
            method,
            self._get_uri_full(uri_relative_with_params),
            data=request_bytes,
            headers=all_headers,
            proxies={self._FIELD_PROXY_HTTPS: self._api_context.proxy_url},
        )

        self._assert_response_success(response)

        if self._api_context.installation_context is not None:
            security.validate_response(
                self._api_context.installation_context.public_key_server,
                response.status_code,
                response.content,
                response.headers
            )

        return self._create_bunq_response_raw(response)
977673
def request(self, api_query, url=None):
        
        api_query['format'] = 'json'
        if url is not None:
            api_url = url + "/api.php"
        else:
            api_url = self.api_url

        size = sum([sys.getsizeof(v) for k, v in iteritems(api_query)])

        if size > (1024 * 8):
            # if request is bigger than 8 kB (the limit is somewhat arbitrary,
            # see https://www.mediawiki.org/wiki/API:Edit#Large_texts) then
            # transmit as multipart message

            req = self._prepare_long_request(url=api_url,
                                             api_query=api_query)
            req.send()
            if self.return_json:
                return req.response.json()
            else:
                return req.response.text
        else:
            auth1 = OAuth1(
                self.consumer_token.key,
                client_secret=self.consumer_token.secret,
                resource_owner_key=session['mwoauth_access_token']['key'],
                resource_owner_secret=session['mwoauth_access_token']['secret'])
            if self.return_json:
                return requests.post(api_url, data=api_query, auth=auth1).json()
            else:
                return requests.post(api_url, data=api_query, auth=auth1).text
801628
def request(params, &block)
      start = Time.now

      dummy_params =  {
        expects: params[:expects],
        method: params[:method],
        body: params[:body]
      }

      text.msg "#{text.color('START', :cyan, :bold)}"
      params.each do |pkey, pvalue|
        text.msg("> #{pkey}: #{pvalue}")
      end

      if params[:token].nil?
        @uname = params[:username]
        @pass = params[:password]
        @cred = "#{@uname}:#{@pass}"
        @final_cred64 = Base64.encode64(@cred)

        @final_hash = { creds: "Basic #{@final_cred64}" }

        response = connection_repo.request(dummy_params, &block)
        text.msg("END(#{(Time.now - start)}s)")
      else

        @tokens = params[:token]
        @final_token = { token: "token #{@tokens}" }
        response = connection_token.request(dummy_params, &block)

        puts response.inspect
        text.msg("END(#{(Time.now - start)}s)")
        # reset (non-persistent) connection
        # @connection_token.reset
      end

      response
    end
503722
def requests_request(method, url, **kwargs):
    """"""
    session = local_sessions.session
    response = session.request(method=method, url=url, **kwargs)
    session.close()
    return response
998356
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
        """"""
        return self.fetch2(path, api, method, params, headers, body)
667421
async def _request(
            self, method: str, endpoint: str, *, headers: dict = None) -> dict:
        """"""
        url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)

        if not headers:
            headers = {}
        headers.update({
            'Host': DEFAULT_HOST,
            'Origin': DEFAULT_ORIGIN,
            'Referer': DEFAULT_ORIGIN,
            'User-Agent': DEFAULT_USER_AGENT,
        })

        async with self._websession.request(
                method,
                url,
                headers=headers,
        ) as resp:
            try:
                resp.raise_for_status()
                return await resp.json(content_type=None)
            except client_exceptions.ClientError as err:
                raise RequestError(
                    'Error requesting data from {0}: {1}'.format(
                        endpoint, err)) from None
1236561
async def api_request(self, url, params):
        """"""
        request = None
        try:
            with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
                request = await self._api_session.get(
                    url, params=params)
            if request.status != 200:
                _LOGGER.error('Error fetching Emby data: %s', request.status)
                return None

            request_json = await request.json()
            if 'error' in request_json:
                _LOGGER.error('Error converting Emby data to json: %s: %s',
                              request_json['error']['code'],
                              request_json['error']['message'])
                return None
            return request_json
        except (aiohttp.ClientError, asyncio.TimeoutError,
                ConnectionRefusedError) as err:
            _LOGGER.error('Error fetching Emby data: %s', err)
            return None
815212
def list_requests(status=None):
    '''
    
    '''
    if status:
        url = '{0}/request?status={1}'.format(_base_url(), status)
    else:
        url = '{0}/request'.format(_base_url())

    reqs = _paginate(url,
                     "requests",
                     method='GET',
                     decode=True,
                     decode_type='json',
                     raise_error=False,
                     header_dict={
                         'X-DC-DEVKEY': _api_key(),
                         'Content-Type': 'application/json',
                     }
    )

    ret = {'requests': reqs}
    return ret
1249446
def create_api_interface_request(self):
        """"""

        return ApiInterfaceRequest(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
508198
def _request(self, data):
        """"""
        return requests.post(self.endpoint, data=data.encode("ascii")).content
523293
def _request_internal(self, command, **kwargs):
        """"""
        args = dict(kwargs)
        if self.ssid:
            args['ssid'] = self.ssid
        method = getattr(self.api, command)
        response = method(**args)
        if response and 'status' in response:
            if response['status'] == 'error':
                raise SubregError(
                    message=response['error']['errormsg'],
                    major=response['error']['errorcode']['major'],
                    minor=response['error']['errorcode']['minor']
                )
            if response['status'] == 'ok':
                return response['data'] if 'data' in response else dict()
            raise Exception("Invalid status found in SOAP response")
        raise Exception('Invalid response')
629321
def _build_request(self, type, commands):
        '''
        
        '''
        request = {}
        headers = {
            'content-type': 'application/json',
        }
        if self.nxargs['connect_over_uds']:
            user = self.nxargs['cookie']
            headers['cookie'] = 'nxapi_auth=' + user + ':local'
            request['url'] = self.NXAPI_UDS_URI_PATH
        else:
            request['url'] = '{transport}://{host}:{port}{uri}'.format(
                transport=self.nxargs['transport'],
                host=self.nxargs['host'],
                port=self.nxargs['port'],
                uri=self.NXAPI_REMOTE_URI_PATH,
            )

        if isinstance(commands, (list, set, tuple)):
            commands = ' ; '.join(commands)
        payload = {}
        payload['ins_api'] = {
            'version': self.NXAPI_VERSION,
            'type': type,
            'chunk': '0',
            'sid': '1',
            'input': commands,
            'output_format': 'json',
        }
        request['headers'] = headers
        request['payload'] = json.dumps(payload)
        request['opts'] = {
            'http_request_timeout': self.nxargs['timeout']
        }
        log.info('request: %s', request)
        return request
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
908801
def request(method = :get, path = '/files/', params = {})
      response = @api_connection.send method, path, params
      response.body
    end