Creating a request with the given arguments

If api_version is set, appends it immediately after host
772656
public function createRequest($httpMethod, $path, $body = null, array $headers = array(), array $options = array())
    {
        $version = (isset($options['api_version']) ? "/".$options['api_version'] : "");

        $path    = $version.$path;

        return $this->client->createRequest($httpMethod, $path, $headers, $body, $options);
    }
1261546
def request(self, api_call, data=None, api_version=None, http_method=None, concurrent_scans_retries=0,
                concurrent_scans_retry_delay=0):
        
        logger.debug('api_call =\n%s' % api_call)
        logger.debug('api_version =\n%s' % api_version)
        logger.debug('data %s =\n %s' % (type(data), str(data)))
        logger.debug('http_method =\n%s' % http_method)
        logger.debug('concurrent_scans_retries =\n%s' % str(concurrent_scans_retries))
        logger.debug('concurrent_scans_retry_delay =\n%s' % str(concurrent_scans_retry_delay))
        concurrent_scans_retries = int(concurrent_scans_retries)
        concurrent_scans_retry_delay = int(concurrent_scans_retry_delay)
        #
        # Determine API version.
        # Preformat call.
        api_call = self.preformat_call(api_call)
        if api_version:
            # API version specified, format API version inputted.
            api_version = self.format_api_version(api_version)
        else:
            # API version not specified, determine automatically.
            api_version = self.which_api_version(api_call)
        #
        # Set up base url.
        url = self.url_api_version(api_version)
        #
        # Set up headers.
        headers = {"X-Requested-With": "Parag Baxi QualysAPI (python) v%s" % (qualysapi.version.__version__,)}
        logger.debug('headers =\n%s' % (str(headers)))
        # Portal API takes in XML text, requiring custom header.
        if api_version in ('am', 'was', 'am2'):
            headers['Content-type'] = 'text/xml'
        #
        # Set up http request method, if not specified.
        if not http_method:
            http_method = self.format_http_method(api_version, api_call, data)
        logger.debug('http_method =\n%s' % http_method)
        #
        # Format API call.
        api_call = self.format_call(api_version, api_call)
        logger.debug('api_call =\n%s' % (api_call))
        # Append api_call to url.
        url += api_call
        #
        # Format data, if applicable.
        if data is not None:
            data = self.format_payload(api_version, data)
        # Make request at least once (more if concurrent_retry is enabled).
        retries = 0
        #
        # set a warning threshold for the rate limit
        rate_warn_threshold = 10
        while retries <= concurrent_scans_retries:
            # Make request.
            logger.debug('url =\n%s' % (str(url)))
            logger.debug('data =\n%s' % (str(data)))
            logger.debug('headers =\n%s' % (str(headers)))
            if http_method == 'get':
                # GET
                logger.debug('GET request.')
                request = self.session.get(url, params=data, auth=self.auth, headers=headers, proxies=self.proxies)
            else:
                # POST
                logger.debug('POST request.')
                # Make POST request.
                request = self.session.post(url, data=data, auth=self.auth, headers=headers, proxies=self.proxies)
            logger.debug('response headers =\n%s' % (str(request.headers)))
            #
            # Remember how many times left user can make against api_call.
            try:
                self.rate_limit_remaining[api_call] = int(request.headers['x-ratelimit-remaining'])
                logger.debug('rate limit for api_call, %s = %s' % (api_call, self.rate_limit_remaining[api_call]))
                if (self.rate_limit_remaining[api_call] > rate_warn_threshold):
                    logger.debug('rate limit for api_call, %s = %s' % (api_call, self.rate_limit_remaining[api_call]))
                elif (self.rate_limit_remaining[api_call] <= rate_warn_threshold) and (
                        self.rate_limit_remaining[api_call] > 0):
                    logger.warning(
                        'Rate limit is about to being reached (remaining api calls = %s)' % self.rate_limit_remaining[
                            api_call])
                elif self.rate_limit_remaining[api_call] <= 0:
                    logger.critical('ATTENTION! RATE LIMIT HAS BEEN REACHED (remaining api calls = %s)!' %
                                    self.rate_limit_remaining[api_call])
            except KeyError as e:
                # Likely a bad api_call.
                logger.debug(e)
                pass
            except TypeError as e:
                # Likely an asset search api_call.
                logger.debug(e)
                pass
            # Response received.
            response = request.text
            logger.debug('response text =\n%s' % (response))
            # Keep track of how many retries.
            retries += 1
            # Check for concurrent scans limit.
            if not ('<responseCode>INVALID_REQUEST</responseCode>' in response and
                    '<errorMessage>You have reached the maximum number of concurrent running scans' in response and
                    '<errorResolution>Please wait until your previous scans have completed</errorResolution>' in response):
                # Did not hit concurrent scan limit.
                break
            else:
                # Hit concurrent scan limit.
                logger.critical(response)
                # If trying again, delay next try by concurrent_scans_retry_delay.
                if retries <= concurrent_scans_retries:
                    logger.warning('Waiting %d seconds until next try.' % concurrent_scans_retry_delay)
                    time.sleep(concurrent_scans_retry_delay)
                    # Inform user of how many retries.
                    logger.critical('Retry #%d' % retries)
                else:
                    # Ran out of retries. Let user know.
                    print('Alert! Ran out of concurrent_scans_retries!')
                    logger.critical('Alert! Ran out of concurrent_scans_retries!')
                    return False
        # Check to see if there was an error.
        try:
            request.raise_for_status()
        except requests.HTTPError as e:
            # Error
            print('Error! Received a 4XX client error or 5XX server error response.')
            print('Content = \n', response)
            logger.error('Content = \n%s' % response)
            print('Headers = \n', request.headers)
            logger.error('Headers = \n%s' % str(request.headers))
            request.raise_for_status()
        if '<RETURN status="FAILED" number="2007">' in response:
            print('Error! Your IP address is not in the list of secure IPs. Manager must include this IP (QualysGuard VM > Users > Security).')
            print('Content = \n', response)
            logger.error('Content = \n%s' % response)
            print('Headers = \n', request.headers)
            logger.error('Headers = \n%s' % str(request.headers))
            return False
        return response
71765
function loadCurrentVersion (options, context) {
  return new Extension(options, context).read()
    .then(function (response) {
      let version = response.sys.version;

      options.version = version;
      return options;
    });
}
941687
def _construct_api_path(self, version):
        

        V2_PATH = 'api/'
        V3_PATH = 'api/s/' + self.site_id + '/'

        if(version == 'v2'):
            return V2_PATH
        if(version == 'v3'):
            return V3_PATH
        if(version == 'v4'):
            return V3_PATH
        if(version == 'v5'):
            return V3_PATH
        else:
            return V2_PATH
10333
def url_api_version(self, api_version):
        
        # Set base url depending on API version.
        if api_version == 1:
            # QualysGuard API v1 url.
            url = "https://%s/msp/" % (self.server,)
        elif api_version == 2:
            # QualysGuard API v2 url.
            url = "https://%s/" % (self.server,)
        elif api_version == 'was':
            # QualysGuard REST v3 API url (Portal API).
            url = "https://%s/qps/rest/3.0/" % (self.server,)
        elif api_version == 'am':
            # QualysGuard REST v1 API url (Portal API).
            url = "https://%s/qps/rest/1.0/" % (self.server,)
        elif api_version == 'am2':
            # QualysGuard REST v1 API url (Portal API).
            url = "https://%s/qps/rest/2.0/" % (self.server,)
        else:
            raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,))
        logger.debug("Base url =\n%s" % (url))
        return url
1046606
def create_version(self, project_id_or_key, version_name, extra_request_params={}):
        
        request_params = extra_request_params
        request_params["name"] = version_name
        return self.do("POST", "projects/{project_id_or_key}/versions",
                       url_params={"project_id_or_key": project_id_or_key},
                       request_params=request_params,
                       )
207337
def increment_api_version_string(api_version_string: nil, increment_by: :patch)
      versions = api_version_string.split(".")
      major = versions[0].to_i
      minor = versions[1].to_i
      patch = versions[2].to_i

      case increment_by
      when :patch
        patch += 1
      when :minor
        minor += 1
        patch = 0
      when :major
        major += 1
        minor = 0
        patch = 0
      end

      new_version_string = [major, minor, patch].join(".")
      return new_version_string
    end
615021
def build_request(name, args)
      build_args(args) if args
      uri = build_url(query_params: @query_params)
      @http = build_http(uri.host, uri.port)
      net_http = Kernel.const_get('Net::HTTP::' + name.to_s.capitalize)
      @request = build_request_headers(net_http.new(uri.request_uri))
      if @request_body &&
         (!@request_headers.key?('Content-Type') ||
          @request_headers['Content-Type'] == 'application/json')

        @request.body = @request_body.to_json
        @request['Content-Type'] = 'application/json'
      elsif !@request_body && (name.to_s == 'post')
        @request['Content-Type'] = ''
      else
        @request.body = @request_body
      end
      @http_options.each do |attribute, value|
        @http.send("#{attribute}=", value)
      end
      make_request(@http, @request)
    end
753832
def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs):
        """"""
        request_version = self.determine_version(request, api_version)
        if request_version:
            request_version = int(request_version)
        versions.get(request_version or False, versions.get(None, not_found))(request, response,
                                                                              api_version=api_version,
                                                                              **kwargs)
1202719
def make_request(name, params=None, version="V001", key=None, api_type="web",
                 fetcher=get_page, base=None, language="en_us"):
    

    params = params or {}
    params["key"] = key or API_KEY
    params["language"] = language

    if not params["key"]:
        raise ValueError("API key not set, please set DOTA2_API_KEY")

    url = url_map("%s%s/%s/" % (base or BASE_URL, name, version), params)
    return fetcher(url)
876072
private AddonActionRequest createRequest(final AddonInfo requestedAddonInfo, final AddonInfo addonInfo,
            final MutableAddonRepository repository,
            final Map<AddonId, AddonRepository> installedAddons)
   {
      final AddonActionRequest request;
      AddonId addon = addonInfo.getAddon();
      if (installedAddons.containsKey(addon))
      {
         // Already contains the installed addon. Update ONLY if the version is SNAPSHOT and if it is the requested
         // addon
         if (Versions.isSnapshot(addon.getVersion()) && addonInfo.equals(requestedAddonInfo))
         {
            AddonRepository addonRepository = installedAddons.get(addon);
            if (repository.equals(addonRepository))
            {
               request = createUpdateRequest(addonInfo, addonInfo, repository, furnace);
            }
            else
            {
               request = createDeployRequest(addonInfo, repository, furnace);
            }
         }
         else
         {
            request = null;
         }
      }
      else
      {
         // Addon is not installed or has a different version
         Entry<AddonId, AddonRepository> differentVersionEntry = null;
         for (Entry<AddonId, AddonRepository> addonEntry : installedAddons.entrySet())
         {
            AddonId addonId = addonEntry.getKey();
            if (addonId.getName().equals(addon.getName()))
            {
               differentVersionEntry = addonEntry;
               break;
            }
         }
         if (differentVersionEntry != null)
         {
            // Avoiding ClassCastExceptions
            Version differentVersion = SingleVersion.valueOf(differentVersionEntry.getKey().getVersion().toString());
            Version addonVersion = SingleVersion.valueOf(addon.getVersion().toString());
            // TODO: Review condition below
            // Update ONLY if it is the requested addon
            if (differentVersion.compareTo(addonVersion) < 0 && addonInfo.equals(requestedAddonInfo))
            {
               if (repository.equals(differentVersionEntry.getValue()))
               {
                  request = createUpdateRequest(info(differentVersionEntry.getKey()), addonInfo, repository, furnace);
               }
               else
               {
                  request = createDeployRequest(addonInfo, repository, furnace);
               }
            }
            else
            {
               // No update needed. Don't do anything with it
               request = null;
            }
         }
         else
         {
            request = createDeployRequest(addonInfo, repository, furnace);
         }
      }
      return request;
   }
297850
def api_version(profile=None, **connection_args):
    '''
    
    '''
    kwargs = _get_kwargs(profile=profile, **connection_args)
    auth_url = kwargs.get('auth_url', kwargs.get('endpoint', None))
    try:
        return salt.utils.http.query(auth_url, decode=True, decode_type='json',
                                     verify_ssl=False)['dict']['version']['id']
    except KeyError:
        return None
133499
def call_api(self, path, **kwargs):
        '''
        
        '''
        if 'key' not in kwargs:
            kwargs['key'] = self.api_key
        req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)

        if req.status_code != requests.codes.ok:
            req.raise_for_status()

        return req.json()
1033905
def _get_api_version(self):
        
        url = "{base_url}/api/server_info".format(base_url=self._base_url())
        server_info = self._make_request(url=url, method="get")
        return server_info["latest_api_version"]
951745
def request(self, url, method="get", format="json", data=None,
                expected_status=None, headers=None, use_xpost=True, **options):
        
        if expected_status is None:
            if method == "get":
                expected_status = 200
            elif method == "post":
                expected_status = 201
            else:
                raise ValueError("No expected status supplied and method unknown.")

        if not url.startswith("http"):
            url = "{self.host}/api/v4/{url}".format(**locals())
        if format is not None:
            options = dict({'format': format}, **options)
        options = {field: value for field, value in options.items() if value is not None}
        headers = dict(headers or {}, Authorization="Token {}".format(self.token))
        #headers['Accept-encoding'] = 'gzip'

        if method == "get" and use_xpost:
            # If method is purely GET, we can use X-HTTP-METHOD-OVERRIDE to send our
            # query via POST. This allows for a large number of parameters to be supplied
            assert(data is None)

            headers.update({"X-HTTP-METHOD-OVERRIDE": method})
            data = options
            options = None
            method = "post"

        r = requests.request(method, url, data=data, params=options, headers=headers)

        log.debug(
            "HTTP {method} {url} (options={options!r}, data={data!r},"
            "headers={headers}) -> {r.status_code}".format(**locals())
        )
        return check(r, expected_status=expected_status)
772005
def do_version():
    """"""
    v = ApiPool.ping.model.Version(
        name=ApiPool().current_server_name,
        version=ApiPool().current_server_api.get_version(),
        container=get_container_version(),
    )
    log.info("/version: " + pprint.pformat(v))
    return v
382845
def upgrade_api(request, client, version):
    """"""

    min_ver, max_ver = api_versions._get_server_version_range(client)
    if min_ver <= api_versions.APIVersion(version) <= max_ver:
        client = _nova.novaclient(request, version)
    return client