Construct API request from parameters and return the response.

    Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
434831
def request(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
    
    if not identifier:
        raise ValueError('identifier/cid cannot be None')
    # If identifier is a list, join with commas into string
    if isinstance(identifier, int):
        identifier = str(identifier)
    if not isinstance(identifier, text_types):
        identifier = ','.join(str(x) for x in identifier)
    # Filter None values from kwargs
    kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
    # Build API URL
    urlid, postdata = None, None
    if namespace == 'sourceid':
        identifier = identifier.replace('/', '.')
    if namespace in ['listkey', 'formula', 'sourceid'] \
            or searchtype == 'xref' \
            or (searchtype and namespace == 'cid') or domain == 'sources':
        urlid = quote(identifier.encode('utf8'))
    else:
        postdata = urlencode([(namespace, identifier)]).encode('utf8')
    comps = filter(None, [API_BASE, domain, searchtype, namespace, urlid, operation, output])
    apiurl = '/'.join(comps)
    if kwargs:
        apiurl += '?%s' % urlencode(kwargs)
    # Make request
    try:
        log.debug('Request URL: %s', apiurl)
        log.debug('Request data: %s', postdata)
        response = urlopen(apiurl, postdata)
        return response
    except HTTPError as e:
        raise PubChemHTTPError(e)
742300
def http_request(path, params)
      token = api_key || Goodreads.configuration[:api_key]

      fail(Goodreads::ConfigurationError, "API key required.") if token.nil?

      params.merge!(format: API_FORMAT, key: token)
      url = "#{API_URL}#{path}"

      resp = RestClient.get(url, params: params) do |response, request, result, &block|
        case response.code
        when 200
          response.return!(&block)
        when 401
          fail(Goodreads::Unauthorized)
        when 403
          fail(Goodreads::Forbidden)
        when 404
          fail(Goodreads::NotFound)
        end
      end

      parse(resp)
    end
825433
def _http_call(self, url, method, data=None, **kwargs):
        
        response = self._http_response(url, method, data=data, **kwargs)
        if not response.content:
            return {}

        return response.json()
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
            }
820349
function request(url, payload) {
  return fetch(url, {
    method: 'POST',
    // set to 1000 b/c no response needed
    timeout: 1000,
    body: JSON.stringify(payload),
  })
  .then((response) => {
    if (response.status === 404) {
      return BbPromise.reject('404 api not found');
    }
    return response.json();
  })
  .then((res) => BbPromise.resolve(res))
  .catch((e) => BbPromise.resolve(e));
}
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)
18966
def _post_response(self, params):
        
        return self._session.post(
            self._api_url, data=params, timeout=self._timeout
        ).json(encoding="utf8")
742053
def make_request(self, request, captcha_response=None):
        
        logger.debug('Prepare API Method request %r', request)
        response = self._send_api_request(request=request,
                                          captcha_response=captcha_response)
        response.raise_for_status()
        response_or_error = json.loads(response.text)
        logger.debug('response: %s', response_or_error)

        if 'error' in response_or_error:
            error_data = response_or_error['error']
            vk_error = VkAPIError(error_data)

            if vk_error.is_captcha_needed():
                captcha_key = self.get_captcha_key(vk_error.captcha_img_url)
                if not captcha_key:
                    raise vk_error

                # Retry http request with captcha info attached
                captcha_response = {
                    'sid': vk_error.captcha_sid,
                    'key': captcha_key,
                }
                return self.make_request(
                    request, captcha_response=captcha_response)

            elif vk_error.is_access_token_incorrect():
                logger.info(
                    'Authorization failed. Access token will be dropped')
                self._access_token = None
                return self.make_request(request)

            else:
                raise vk_error
        elif 'execute_errors' in response_or_error:
            # can take place while running .execute vk method
            # See more: https://vk.com/dev/execute
            raise VkAPIError(response_or_error['execute_errors'][0])
        elif 'response' in response_or_error:
            return response_or_error['response']
1103114
def request(operation, version = nil, params = {})
      response = open(request_url(operation, version, params), @http_opts) do |f|
        @raw_response = f.read
        JSON.parse(@raw_response)
      end
      unless response['Header']['Status'] == 'Success'
        raise ApiError.new(response['Header']['Status'], response['Header']['StatusMsg']) 
      end
      extract_result(response, operation)
    end
661675
def _make_api_call(self, method, url, json_params=None):
        
        if self.verbose is True:
            print "\ncrossbarhttp: Request: %s %s" % (method, 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 "crossbarhttp: Params: " + encoded_params

        if self.key is not None and self.secret is not None and encoded_params is not None:
            signature, nonce, timestamp = self._compute_signature(encoded_params)
            params = urllib.urlencode({
                "timestamp": timestamp,
                "seq": str(self.sequence),
                "nonce": nonce,
                "signature": signature,
                "key": self.key
            })
            if self.verbose is True:
                print "crossbarhttp: Signature Params: " + params
            url += "?" + params

        # TODO: I can't figure out what this is.  Guessing it is a number you increment on every call
        self.sequence += 1

        try:
            request = urllib2.Request(url, encoded_params, headers)
            request.get_method = lambda: method
            response = urllib2.urlopen(request).read()
            if self.verbose is True:
                print "crossbarhttp: Response: " + response

            return json.loads(response)

        except urllib2.HTTPError, e:
            if e.code == 400:
                raise ClientMissingParams(str(e))
            elif e.code == 401:
                raise ClientSignatureError(str(e))
            else:
                raise ClientBadUrl(str(e))
        except urllib2.URLError, e:
            raise ClientBadHost(str(e))
1022232
def request(self, method, params=None):
        
        if params is None:
            params = {}
        if not self.phab_session:
            self.connect()
        url = '%s/api/%s' % (self.host, method)
        params['__conduit__'] = self.phab_session
        req = self.req_session.post(url, data={
            'params': json.dumps(params),
            'output': 'json',
        })
        return json.loads(
            req.content.decode(),
            object_pairs_hook=collections.OrderedDict
        )['result']
345137
def request(api, args)
      uri = api == :uploading ? UPLOAD_URI : API_URI
      args[:method] = "smugmug.#{api}" unless api == :uploading

      http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass)
      http.set_debug_output(@config[:debug_output]) if @config[:debug_output]

      # Configure HTTPS if needed
      if uri.scheme == "https"
        http.use_ssl = true

        if @config[:http] and @config[:http][:verify_mode]
          http.verify_mode = @config[:http][:verify_mode]
          http.ca_file = @config[:http][:ca_file]
          http.ca_path = @config[:http][:ca_path]
        else
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
      end

      # Upload request, which requires special handling
      if api == :uploading
        postdata = args.delete(:content)
        headers = @headers.merge("Content-Length" => postdata.length.to_s, "Content-MD5" => Digest::MD5.hexdigest(postdata), "X-Smug-Version" => "1.3.0", "X-Smug-ResponseType" => "JSON")

        UPLOAD_HEADERS.each do |key|
          next unless args[key] and args[key] != ""
          headers["X-Smug-#{key}"] = args[key].to_s
        end

        oauth = self.sign_request("POST", uri, nil)
        headers["Authorization"] = "OAuth oauth_consumer_key=\"#{oauth["oauth_consumer_key"]}\", oauth_nonce=\"#{oauth["oauth_nonce"]}\", oauth_signature_method=\"#{oauth["oauth_signature_method"]}\", oauth_signature=\"#{oauth["oauth_signature"]}\", oauth_timestamp=\"#{oauth["oauth_timestamp"]}\", oauth_version=\"#{oauth["oauth_version"]}\", oauth_token=\"#{oauth["oauth_token"]}\""

      # Normal API method
      else
        postdata = self.sign_request("POST", uri, args)
        headers = @headers
      end

      response = http.request_post(uri.request_uri, postdata, headers)
      if response.code == "204"
        return nil
      elsif response.code != "200"
        raise SmugMug::HTTPError.new("HTTP #{response.code}, #{response.message}", response.code, response.message)
      end

      # Check for GZIP encoding
      if response.header["content-encoding"] == "gzip"
        begin
          body = Zlib::GzipReader.new(StringIO.new(response.body)).read
        rescue Zlib::GzipFile::Error
          raise
        end
      else
        body = response.body
      end

      return nil if body == ""

      data = JSON.parse(body)

      if data["stat"] == "fail"
        # Special casing for SmugMug being in Read only mode
        if data["code"] == 99
          raise SmugMug::ReadonlyModeError.new("SmugMug is currently in read only mode, try again later")
        end

        klass = OAUTH_ERRORS[data["code"]] ? SmugMug::OAuthError : SmugMug::RequestError
        raise klass.new("Error ##{data["code"]}, #{data["message"]}", data["code"], data["message"])
      end

      data.delete("stat")
      data.delete("method")

      # smugmug.albums.changeSettings at the least doesn't return any data
      return nil if data.length == 0

      # It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues
      data.each do |_, value|
        return value
      end
    end
919264
def _rest_request(self, url, object_path, service_name, requests_config, tags, *args, **kwargs):
        
        service_check_tags = ['url:%s' % self._get_url_base(url)] + tags

        if object_path:
            url = self._join_url_dir(url, object_path)

        # Load SSL configuration, if available.
        # ssl_verify can be a bool or a string
        # (http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification)
        if isinstance(requests_config.ssl_verify, bool) or isinstance(requests_config.ssl_verify, str):
            verify = requests_config.ssl_verify
        else:
            verify = None
        if requests_config.ssl_cert and requests_config.ssl_key:
            cert = (requests_config.ssl_cert, requests_config.ssl_key)
        elif requests_config.ssl_cert:
            cert = requests_config.ssl_cert
        else:
            cert = None

        # Add args to the url
        if args:
            for directory in args:
                url = self._join_url_dir(url, directory)

        # Add kwargs as arguments
        if kwargs:
            query = '&'.join(['{0}={1}'.format(key, value) for key, value in iteritems(kwargs)])
            url = urljoin(url, '?' + query)

        old_keytab_path = None
        if requests_config.kerberos_keytab:
            old_keytab_path = os.getenv('KRB5_CLIENT_KTNAME')
            os.environ['KRB5_CLIENT_KTNAME'] = requests_config.kerberos_keytab

        try:
            self.log.debug('Spark check URL: %s' % url)
            response = requests.get(url, auth=requests_config.auth, verify=verify, cert=cert)

            response.raise_for_status()

        except Timeout as e:
            self.service_check(
                service_name,
                AgentCheck.CRITICAL,
                tags=service_check_tags,
                message='Request timeout: {0}, {1}'.format(url, e),
            )
            raise

        except (HTTPError, InvalidURL, ConnectionError) as e:
            self.service_check(
                service_name,
                AgentCheck.CRITICAL,
                tags=service_check_tags,
                message='Request failed: {0}, {1}'.format(url, e),
            )
            raise

        except ValueError as e:
            self.service_check(service_name, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
            raise

        else:
            return response

        finally:
            if old_keytab_path is not None:
                os.environ['KRB5_CLIENT_KTNAME'] = old_keytab_path
853020
def make_request(self, path, params=None, data=None, method=None):
        '''
        
        '''
        # Setup values
        url = self.build_url(path, params)
        client_log.debug('Requesting:  %s' % url)
        method = method or 'GET'
        body = None
        headers = {}

        if data:
            method = 'POST'
            body = urlencode(data)
            headers = {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            }

        client_log.debug('Request Method:  %s' % method)
        client_log.debug('Request Body(Data):  %s' % data)
        client_log.debug('Request Body(Raw):  %s' % body)

        # Setup http client
        h = httplib2.Http(cache=self.cache, timeout=self.timeout)
        #h.add_credentials(self.username, self.password)
        # Skip the normal http client behavior and send auth headers immediately
        # to save an http request.
        headers['Authorization'] = "Basic %s" % base64.standard_b64encode(self.username + ':' + self.password).strip()

        # Make request
        response, content = h.request(url, method, body=body, headers=headers)
        status = response.status
        client_log.debug('Response Status:  %d' % status)
        client_log.debug('Response Content:  %s' % content)
        if status != 200 and status != 302:
            exception_class = CheddarError
            if status == 401:
                exception_class = AccessDenied
            elif status == 400:
                exception_class = BadRequest
            elif status == 404:
                exception_class = NotFound
            elif status == 412:
                exception_class = PreconditionFailed
            elif status == 500:
                exception_class = CheddarFailure
            elif status == 502:
                exception_class = NaughtyGateway
            elif status == 422:
                exception_class = UnprocessableEntity

            raise exception_class(response, content)

        response.content = content
        return response
626260
def _req(self, method="get", verb=None, headers={}, params={}, data={}):
        
        url = self.BASE_URL.format(verb=verb)
        request_headers = {"content-type": "application/json"}
        request_params = {"api_key": self.API_KEY}
        request_headers.update(headers)
        request_params.update(params)
        return getattr(requests, method)(
            url, params=request_params, headers=request_headers, data=data
        )
649227
def _do_request(self, url, params=None, data=None, headers=None):
        

        if not headers:
            headers = {'content-type': 'application/json'}

        try:
            response = requests.get(
                url, params=params, data=data, headers=headers)
        except:
            return None

        if response.status_code == 200:
            return response
1145188
def request(self, method, path, params=None, headers=None, body=None):
        
        if not headers:
            headers = {}
        if not params:
            params = {}

        headers["Accept"] = "application/json"
        headers["Accept-Version"] = "^1.15.0"
        if self.auth_token:
            headers["Authorization"] = "Bearer {0}".format(self.auth_token)

        path = self.url + path
        params = self.flatten_params(params)
        response = requests.request(method, path, params=params, headers=headers, json=body)

        result = response.text
        try:
            result = response.json()
        except Exception:
            pass

        if response.status_code >= 400:
            raise LosantError(response.status_code, result)

        return result