Call an API with HTTP POST method and Service Owner credentials.
431302
private <TResponse> TResponse callServiceOwnerPostApi(
            String path, Map<String, String> queryParams,
            Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callPostApi(mServiceOwnerCredentials, path, queryParams, requestBody, responseClass);
    }
506358
def post(self, url, postParameters=None, urlParameters=None):
        
        if not self.access_token:
            raise IOError("No authorized client available.")
        if not self.action_token:
            raise IOError("Need to generate action token.")
        if urlParameters is None:
            urlParameters = {}
        headers = {'Authorization': 'Bearer ' + self.access_token,
                   'Content-Type': 'application/x-www-form-urlencoded'}
        postParameters.update({'T':self.action_token})
        request = requests.post(url + '?' + self.getParameters(urlParameters),
                                data=postParameters, headers=headers)
        if request.status_code != 200:
            return None
        else:
            return toUnicode(request.text)
660862
def POST_query(self, req_hook, req_args):
        '''  '''
        # HTTP POST queries require keyManagerTokens and sessionTokens
        headers = {'Content-Type': 'application/json',
                   'sessionToken': self.__session__,
                   'keyManagerToken': self.__keymngr__}

        # HTTP POST query to keymanager authenticate API
        try:
            if req_args is None:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         verify=True)
            else:
                response = requests.post(self.__url__ + req_hook,
                                         headers=headers,
                                         data=req_args,
                                         verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            return '500', 'Internal Error in RESTful.POST_query()'
        # return the token
        return response.status_code, response.text
669546
def call_api(self,
                 action,
                 params=None,
                 method=('API', 'POST', 'application/x-www-form-urlencoded'),
                 **kwargs):
        
        urltype, methodname, content_type = method
        if urltype == 'SMS':
            url = self.sms_host
        else:
            url = self.api_host
        if content_type == 'application/json':
            data = json.dumps(params)
        else:
            data = self._filter_params(params)
        return self._http_call(
            url=url + action,
            method=methodname,
            data=data,
            headers=self._headers(content_type),
            **kwargs)
638576
def api(self, name, url, **kwargs):
        """"""
        if name not in self._apis:
            raise ValueError('API name must be one of {0}, not {1!r}.'.format(
                tuple(self._apis), name))
        fields = kwargs.get('fields')
        timeout = kwargs.get('timeout')
        text = kwargs.get('text')
        html = kwargs.get('html')
        if text and html:
            raise ValueError(u'Both `text` and `html` arguments provided!')
        params = {'url': url, 'token': self._token}
        if timeout:
            params['timeout'] = timeout
        if fields:
            if not isinstance(fields, str):
                fields = ','.join(sorted(fields))
            params['fields'] = fields
        url = self.endpoint(name)
        if text or html:
            content_type = html and 'text/html' or 'text/plain'
            return self._post(url, text or html, content_type, params=params)
        return self._get(url, params=params)
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))
107223
def user_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/users.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
1214986
def _api_request(self, uri, method, **kwargs):
        
        id_svc = self.identity
        if not all((self.management_url, id_svc.token, id_svc.tenant_id)):
            id_svc.authenticate()

        if not self.management_url:
            # We've authenticated but no management_url has been set. This
            # indicates that the service is not available.
            raise exc.ServiceNotAvailable("The '%s' service is not available."
                    % self)
        if uri.startswith("http"):
            parsed = list(urllib.parse.urlparse(uri))
            for pos, item in enumerate(parsed):
                if pos < 2:
                    # Don't escape the scheme or netloc
                    continue
                parsed[pos] = _safe_quote(parsed[pos])
            safe_uri = urllib.parse.urlunparse(parsed)
        else:
            safe_uri = "%s%s" % (self.management_url, _safe_quote(uri))
        # Perform the request once. If we get a 401 back then it
        # might be because the auth token expired, so try to
        # re-authenticate and try again. If it still fails, bail.
        try:
            kwargs.setdefault("headers", {})["X-Auth-Token"] = id_svc.token
            if id_svc.tenant_id:
                kwargs["headers"]["X-Auth-Project-Id"] = id_svc.tenant_id
            resp, body = self._time_request(safe_uri, method, **kwargs)
            return resp, body
        except exc.Unauthorized as ex:
            try:
                id_svc.authenticate()
                kwargs["headers"]["X-Auth-Token"] = id_svc.token
                resp, body = self._time_request(safe_uri, method, **kwargs)
                return resp, body
            except exc.Unauthorized:
                raise ex
1104833
def _make_request(
            self, api_resource, method='GET', params=None, **kwargs):
        
        if kwargs.get('json'):
            headers = {
                'Authorization': 'Bearer {}'.format(self._token),
                'Content-Type': 'application/json'
            }
        else:
            headers = {
                'Authorization': 'Bearer {}'.format(self._token)
            }

        response = requests.request(
            method=method,
            url='{0}{1}'.format(self.BASE_API_URL, api_resource),
            headers=headers,
            params=params,
            **kwargs
        )

        if response.status_code >= 400:
            error_response = response.json()

            raise(ToshlException(
                status_code=response.status_code,
                error_id=error_response['error_id'],
                error_description=error_response['description'],
                extra_info=error_response.get('fields')))

        return response
125068
async def api_post(self, url, params):
        """"""
        post = None
        try:
            with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
                post = await self._api_session.post(
                    url, params=params)
            if post.status != 204:
                _LOGGER.error('Error posting Emby data: %s', post.status)
                return None

            post_result = await post.text()
            return post_result

        except (aiohttp.ClientError, asyncio.TimeoutError,
                ConnectionRefusedError) as err:
            _LOGGER.error('Error posting Emby data: %s', err)
            return None
51450
private static BasicCredentials createServiceOwnerCredentials(AuthleteConfiguration configuration)
    {
        // API key and API secret of a Service Owner.
        String key    = configuration.getServiceOwnerApiKey();
        String secret = configuration.getServiceOwnerApiSecret();

        return new BasicCredentials(key, secret);
    }
106705
private <TResponse> void callDeleteApi(
            BasicCredentials credentials, String path,
            Map<String, String> queryParams) throws AuthleteApiException
    {
        callApi(HttpMethod.DELETE, credentials, path, queryParams, (Object)null, (Class<TResponse>)null);
    }
840987
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()
            );
        }

        // Set json
        if (($json = $this->getJson()) != null) {
            $options['json'] = $json;
            $this->setAccept('application/json');
        }

        if (($formParams = $this->getFormParams()) != null) {
            $options['body'] = $formParams;
            $this->setContentType('application/x-www-form-urlencoded');
        }

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

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

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

        $response = $this->getHttpClient()->send($request);

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

        $this->setData($response->json());
    }
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)
537557
def make_post_request(self, url, auth, json_payload):
        """"""
        response = requests.post(url, auth=auth, json=json_payload)
        return response.json()
336621
private <TResponse> TResponse callServicePostApi(
            String path, Map<String, String> queryParams,
            Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callPostApi(mServiceCredentials, path, queryParams, requestBody, responseClass);
    }
1140847
def fetch(method, uri, params_prefix=None, **params):
    """"""
    params = _prepare_params(params, params_prefix)

    if method == "POST" or method == "PUT":
        r_data = {"data": params}
    else:
        r_data = {"params": params}

    # build the HTTP request and use basic authentication
    url = "https://%s/%s.json" % (CHALLONGE_API_URL, uri)

    try:
        response = request(
            method,
            url,
            auth=get_credentials(),
            **r_data)
        response.raise_for_status()
    except HTTPError:
        if response.status_code != 422:
            response.raise_for_status()
        # wrap up application-level errors
        doc = response.json()
        if doc.get("errors"):
            raise ChallongeException(*doc['errors'])

    return response