Get API method response for a resource in the given API

    CLI Example:

    .. code-block:: bash

        salt myminion boto_apigateway.describe_api_method_response restApiId resourcePath httpMethod statusCode
495198
def describe_api_method_response(restApiId, resourcePath, httpMethod, statusCode,
                                 region=None, key=None, keyid=None, profile=None):
    '''
    

    '''
    try:
        resource = describe_api_resource(restApiId, resourcePath, region=region,
                                         key=key, keyid=keyid, profile=profile).get('resource')
        if resource:
            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
            response = conn.get_method_response(restApiId=restApiId, resourceId=resource['id'],
                                                httpMethod=httpMethod, statusCode=str(statusCode))  # future lint: disable=blacklisted-function
            return {'response': _convert_datetime_str(response)}
        return {'error': 'no such resource'}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
702351
def api_response(resource, optional_arg = nil)
      raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty?

      begin
        res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}")

        if !res.success? || res.body.has_key?("error")
          raise_exception(res)
        else
          return res.body
        end
      rescue => error
        raise Exception, "There was an error: #{error.message}"
      end
    end
232624
def get(api_code=None):
    
    
    resource = 'stats?format=json'
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = util.call_api(resource)
    json_response = json.loads(response)
    return Stats(json_response)
181982
def _resolve_api_id(self):
        '''
        
        '''
        apis = __salt__['boto_apigateway.describe_apis'](name=self.rest_api_name,
                                                         description=_Swagger.AWS_API_DESCRIPTION,
                                                         **self._common_aws_args).get('restapi')
        if apis:
            if len(apis) == 1:
                self.restApiId = apis[0].get('id')
            else:
                raise ValueError('Multiple APIs matching given name {0} and '
                                 'description {1}'.format(self.rest_api_name, self.info_json))
499934
def delete_api_method_response(restApiId, resourcePath, httpMethod, statusCode,
                               region=None, key=None, keyid=None, profile=None):
    '''
    

    '''
    try:
        resource = describe_api_resource(restApiId, resourcePath, region=region,
                                         key=key, keyid=keyid, profile=profile).get('resource')
        if resource:
            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
            conn.delete_method_response(restApiId=restApiId, resourceId=resource['id'],
                                        httpMethod=httpMethod, statusCode=str(statusCode))  # future lint: disable=blacklisted-function
            return {'deleted': True}
        return {'deleted': False, 'error': 'no such resource'}
    except ClientError as e:
        return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
752605
def _request(self, method, resource_uri, **kwargs):
        
        data = kwargs.get('data')
        response = method(self.API_BASE_URL + resource_uri,
                          json=data, headers=self.headers)
        response.raise_for_status()
        return response.json()
1270807
def httpapi_request(client, **params) -> 'Response':
    
    return requests.get(
        _HTTPAPI,
        params={
            'client': client.name,
            'clientver': client.version,
            'protover': 1,
            **params
        })
1288674
def get_update_api(self, resource):
        

        update_api = {
            'path': '/%s/{id}/' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            'operations': [
                {
                    'httpMethod': 'PUT',
                    'nickname': 'update%ss' % resource.model
                    .__name__,
                    'summary': 'Update %ss' % resource.model.__name__,
                    'parameters': [
                        {
                            'paramType': 'path', 
                            'name': 'id',
                            'description': '%s id' % (resource.model.__name__),
                            'dataType': 'int',
                            'required': True,
                            'allowMultiple': False,
                        },
                        {
                            'description': '%s object' % (resource.model.__name__),
                            'paramType': 'body',
                            'required': True,
                            'allowMultiple': False,
                            'dataType': resource.model.__name__
                        }
                    ]
                }
            ]
        }

        return update_api
537327
def _get_action_from_method_and_request_uri(self, method, request_uri):
        

        # service response class should have 'SERVICE_NAME' class member,
        # if you want to get action from method and url
        if not hasattr(self, 'SERVICE_NAME'):
            return None
        service = self.SERVICE_NAME
        conn = boto3.client(service, region_name=self.region)

        # make cache if it does not exist yet
        if not hasattr(self, 'method_urls'):
            self.method_urls = defaultdict(lambda: defaultdict(str))
            op_names = conn._service_model.operation_names
            for op_name in op_names:
                op_model = conn._service_model.operation_model(op_name)
                _method = op_model.http['method']
                uri_regexp = self.uri_to_regexp(op_model.http['requestUri'])
                self.method_urls[_method][uri_regexp] = op_model.name
        regexp_and_names = self.method_urls[method]
        for regexp, name in regexp_and_names.items():
            match = re.match(regexp, request_uri)
            self.uri_match = match
            if match:
                return name
        return None
595528
def _get_response(self, **kwargs):
        
        # pylint: disable=E1101
        url = self.read_url + "?output=JSON&token=%s" % self.read_token
        for key in kwargs:
            if key and kwargs[key]:
                val = kwargs[key]
                if isinstance(val, (list, tuple)):
                    val = ",".join(val)
                url += "&%s=%s" % (key, val)
        self._api_url = url
        req = urllib2.urlopen(url)
        data = simplejson.loads(req.read())
        self._api_raw_data = data
        if data and data.get('error', None):
            exceptions.BrightcoveError.raise_exception(
                data['error'])
        if data == None:
            raise exceptions.NoDataFoundError(
                "No data found for %s" % repr(kwargs))
        return data
262102
def get_function_in_responses(service, operation, protocol):
    
    client = boto3.client(service)

    aws_operation_name = to_upper_camel_case(operation)
    op_model = client._service_model.operation_model(aws_operation_name)
    if not hasattr(op_model.output_shape, 'members'):
        outputs = {}
    else:
        outputs = op_model.output_shape.members
    inputs = op_model.input_shape.members
    input_names = [to_snake_case(_) for _ in inputs.keys() if _ not in INPUT_IGNORED_IN_BACKEND]
    output_names = [to_snake_case(_) for _ in outputs.keys() if _ not in OUTPUT_IGNORED_IN_BACKEND]
    body = '\ndef {}(self):\n'.format(operation)

    for input_name, input_type in inputs.items():
        type_name = input_type.type_name
        if type_name == 'integer':
            arg_line_tmpl = '    {} = self._get_int_param("{}")\n'
        elif type_name == 'list':
            arg_line_tmpl = '    {} = self._get_list_prefix("{}.member")\n'
        else:
            arg_line_tmpl = '    {} = self._get_param("{}")\n'
        body += arg_line_tmpl.format(to_snake_case(input_name), input_name)
    if output_names:
        body += '    {} = self.{}_backend.{}(\n'.format(', '.join(output_names), get_escaped_service(service), operation)
    else:
        body += '    self.{}_backend.{}(\n'.format(get_escaped_service(service), operation)
    for input_name in input_names:
        body += '        {}={},\n'.format(input_name, input_name)

    body += '    )\n'
    if protocol == 'query':
        body += '    template = self.response_template({}_TEMPLATE)\n'.format(operation.upper())
        body += '    return template.render({})\n'.format(
            ', '.join(['{}={}'.format(_, _) for _ in output_names])
        )
    elif protocol in ['json', 'rest-json']:
        body += '    # TODO: adjust response\n'
        body += '    return json.dumps(dict({}))\n'.format(', '.join(['{}={}'.format(to_lower_camel_case(_), _) for _ in output_names]))
    return body
143753
def _fetch_remote_rest_api_gateway_responses(provider, rest_api)
      resources = _client(provider).get_gateway_responses(
        { rest_api_id: rest_api[:_terraform_id] }
      )['items']
      resources.map(&:to_h).map do |gr|
        gr[:_terraform_id] = gr[:id]
        gr[:_geo_id]       = "#{rest_api[:_geo_id]}::#{gr[:response_type]}"
        gr
      end
    end
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
            }
406856
def json_call(cls, method, url, **kwargs):
        
        # retrieve api key if needed
        empty_key = kwargs.pop('empty_key', False)
        send_key = kwargs.pop('send_key', True)
        return_header = kwargs.pop('return_header', False)
        try:
            apikey = cls.get('apirest.key')
            if not apikey and not empty_key:
                cls.echo("No apikey found for REST API, please use "
                         "'gandi setup' command")
                sys.exit(1)
            if send_key:
                if 'headers' in kwargs:
                    kwargs['headers'].update({'X-Api-Key': apikey})
                else:
                    kwargs['headers'] = {'X-Api-Key': apikey}
        except MissingConfiguration:
            if not empty_key:
                return []
        # make the call
        cls.debug('calling url: %s %s' % (method, url))
        cls.debug('with params: %r' % kwargs)
        try:
            resp, resp_headers = JsonClient.request(method, url, **kwargs)
            cls.dump('responded: %r' % resp)
            if return_header:
                return resp, resp_headers
            return resp
        except APICallFailed as err:
            cls.echo('An error occured during call: %s' % err.errors)
            sys.exit(1)
987388
def _call(self, resource_url, params=None):
        
        
        url = "%s%s" % (self._endpoint(), resource_url)
        if params:
            url += "?%s&%s" % (params, self._auth())
        else:
            url += "?%s" % self._auth()
        return requests.get(url)
872467
def get_response(self, action, params, path='/', parent=None,
                     verb='GET', list_marker='Set'):
        
        if not parent:
            parent = self
        response = self.make_request(action, params, path, verb)
        body = response.read()
        boto.log.debug(body)
        if response.status == 200:
            e = boto.jsonresponse.Element(list_marker=list_marker,
                                          pythonize_name=True)
            h = boto.jsonresponse.XmlHandler(e, parent)
            h.parse(body)
            return e
        else:
            boto.log.error('%s %s' % (response.status, response.reason))
            boto.log.error('%s' % body)
            raise self.ResponseError(response.status, response.reason, body)
1219042
def generate_boto3_response(operation):
    
    def _boto3_request(method):
        @wraps(method)
        def f(self, *args, **kwargs):
            rendered = method(self, *args, **kwargs)
            if 'json' in self.headers.get('Content-Type', []):
                self.response_headers.update(
                    {'x-amzn-requestid': '2690d7eb-ed86-11dd-9877-6fad448a8419',
                     'date': datetime.now(pytz.utc).strftime('%a, %d %b %Y %H:%M:%S %Z'),
                     'content-type': 'application/x-amz-json-1.1'})
                resp = xml_to_json_response(
                    self.aws_service_spec, operation, rendered)
                return '' if resp is None else json.dumps(resp)
            return rendered
        return f
    return _boto3_request