From an api definition object create the related api call method
    that will validate the arguments for the api call and then
    dynamically dispatch the request to the appropriate requests module
    convenience method for the specific HTTP verb .
337617
def create_async_api_call_func(api, verb):
    

    # Scopes some local context in which we can build
    # request functions with reflection that primed with
    # some static parameters.
    def api_call_func(self, **kwargs):

        def _async_call_handler():
            api_method = getattr(self, api_method_name(verb, api))
            return api_method(**kwargs)

        return self._executor.submit(_async_call_handler)

    method_name = async_api_method_name(verb, api)

    api_call_func.__name__ = method_name
    api_call_func.__doc__ = "{}\nParameters:\n  {}".format(
        method_name, '\n  '.join(api.request_classes[verb]().keys()))

    return api_call_func
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
1372821
function Api(spec, options) {
  if (!(this instanceof Api)) {
    return new Api(spec, options);
  }

  if (typeof spec !== 'object') {
    throw new Error('api spec must be an object');
  }

  options = options || {};

  // path alias for both resourcePath and doc path
  if (spec.path) {
    if (!spec.resourcePath) spec.resourcePath = spec.path;
    if (!options.path) options.path = spec.path;
    delete spec.path;
  }

  // allow user to pass description in spec
  if (spec.description) {
    if (!options.description) options.description = spec.description;
    delete spec.description;
  }

  // user resourcePath for doc path if not set
  if (!options.path && spec.resourcePath) {
    options.path = spec.resourcePath;
  }

  debug('create api %s', spec.resourcePath, spec);

  this.env = new Environment();

  this.spec = spec;
  this.list = [];
  this.options = options;

  this.middleware = {};
  this.models = {};
  this.nicknames = {};
  this.resources = {};
}
1018304
def execute(request_method, path, api_version, data, headers) # :nodoc:
      request.public_send(
        request_method,
        PagSeguro.api_url("#{api_version}/#{path}"),
        extended_data(data),
        extended_headers(request_method, headers)
      )
    end
921422
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Delete method must happen with POST not with GET
        if request.method == 'POST':
            # Check if this is a webservice request
            self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
            self.json_worker = self.__authtoken or (self.json is True)
            # Call the base implementation
            return super(GenDelete, self).dispatch(request, **kwargs)
        else:
            json_answer = json.dumps({
                'error': True,
                'errortxt': _('Method not allowed, use POST to delete or DELETE on the detail url'),
                })
            return HttpResponse(json_answer, content_type='application/json')
1310767
def dispatch_request(self, *args, **kwargs):
        
        self.args = args
        self.kwargs = kwargs
        self.meth = request.method.lower()
        self.resource = current_app.blueprints.get(request.blueprint, None)

        if not any([self.meth in self.methods, self.meth.upper() in self.methods]):
            return self.return_error(405)

        self.process_before_request_hooks()

        resp = super(Endpoint, self).dispatch_request(*args, **kwargs)
        resp = self.make_response(resp)

        resp = self.process_after_request_hooks(resp)

        return resp
168934
def _rest_dispatch(self, request, response):
        # type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None
        
        # Extract request information
        http_verb = request.get_command()
        sub_path = request.get_sub_path()

        # Find the best matching method, according to the number of
        # readable arguments
        max_valid_args = -1
        best_method = None
        best_args = None
        best_match = None

        for route, method in self.__routes.get(http_verb, {}).items():
            # Parse the request path
            match = route.match(sub_path)
            if not match:
                continue

            # Count the number of valid arguments
            method_args = self.__methods_args[method]
            nb_valid_args = 0
            for name in method_args:
                try:
                    match.group(name)
                    nb_valid_args += 1
                except IndexError:
                    # Argument not found
                    pass

            if nb_valid_args > max_valid_args:
                # Found a better match
                max_valid_args = nb_valid_args
                best_method = method
                best_args = method_args
                best_match = match

        if best_method is None:
            # No match: return a 404 plain text error
            response.send_content(
                404,
                "No method to handle path {0}".format(sub_path),
                "text/plain",
            )
        else:
            # Found a method
            # ... convert arguments
            kwargs = {}
            if best_args:
                for name, converter in best_args.items():
                    try:
                        str_value = best_match.group(name)
                    except IndexError:
                        # Argument is missing: do nothing
                        pass
                    else:
                        if str_value:
                            # Keep the default value when an argument is
                            # missing, i.e. don't give it in kwargs
                            if converter is not None:
                                # Convert the argument
                                kwargs[name] = converter(str_value)
                            else:
                                # Use the string value as is
                                kwargs[name] = str_value

            # Prepare positional arguments
            extra_pos_args = []
            if kwargs:
                # Ignore the first two parameters (request and response)
                method_args = get_method_arguments(best_method).args[:2]
                for pos_arg in method_args:
                    try:
                        extra_pos_args.append(kwargs.pop(pos_arg))
                    except KeyError:
                        pass

            # ... call the method (exceptions will be handled by the server)
            best_method(request, response, *extra_pos_args, **kwargs)
119491
def call_api(path, params = {})
      raise ArgumentError, 'You must include an HTTP method' unless params[:method]
      raise InvalidConnection, 'You have not authenticated and have no token' unless @token
      headers = {
        'Content-Type' => 'application/json',
        'Authorization' => "Bearer #{@token}"
      }
      headers.merge!(params[:headers]) if params[:headers]

      arguments = {headers: headers}
      arguments.merge!({body: params[:body].to_json}) if params[:body]
      arguments.merge!({query: params[:query]}) if params[:query]

      HTTParty.send params[:method], url(path), arguments
    end
294749
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Check if this is a REST query to pusth the answer to responde in JSON
        if bool(self.request.META.get('HTTP_X_REST', False)):
            self.json = True

        # Check if this is a REST query to add an element
        if self.request.method in ['PUT', 'DELETE']:
            if self.request.method == 'PUT':
                action = 'edit'
            else:
                action = 'delete'

            # Set new method
            self.request.method == 'POST'

            # Find the URL
            target = get_class(resolve("{}/{}".format(self.request.META.get("REQUEST_URI"), action)).func)

            # Make sure we will answer as an API
            target.json = True

            # Lets go for it
            return target.as_view()(self.request, pk=kwargs.get('pk'))

        # Detect if we have to answer in json
        self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
        self.json_worker = self.__authtoken or (self.json is True)

        # Check if this is an AJAX request
        if (request.is_ajax() or self.json_worker) and request.body:
            request.POST = json.loads(request.body)

        # Set class internal variables
        self._setup(request)

        # Call the base implementation
        return super(GenDetail, self).dispatch(request, **kwargs)
1049029
def _do_api_call(self, call_type=u'', id = None):
        
        endpoint = None
        url = None
        # print "call_type %s" % (call_type)
        if call_type == u'load':
            endpoint = self.get_endpoint("self")
            if id is None:
                raise APIException("LOAD_IDNOTSET", "could not load object")
        elif call_type == u'delete' or (call_type == u"destroy"):
            endpoint = self.get_endpoint("destroy")
            if id is None:
                raise APIException("DELETE_IDNOTSET", "could not delete object")
        elif call_type == u'update':
            endpoint = self.get_endpoint("update")
            if id is None:
                raise APIException("UPDATE_IDNOTSET", "could not load object")
        elif call_type == u'create':
            endpoint = self.get_endpoint("create")
            url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'])
            # post?
        elif call_type == u'schema':
            # add schema gethering functionality 
            # hackisch
            endpoint = self.get_endpoint("create")
            url = u"%s%s%s/schema" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'])
            endpoint['method'] = u'GET'    
        if id is not None:
            url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'].replace(u"{id}",id))
        ## excecute the api request
        payload = self.to_json()
        if u'method' in endpoint.keys():
            method = endpoint['method']
        else:
            method = u'GET'
        # request raises exceptions if something goes wrong
        obj = None
        try:
            # dbg
            msg = u"url: %s method:%s p: %s" % (url, method, payload)
            #print msg
            response = self.__api__.request(url, method, data=payload)
            #load update create success
            if ((response.status_code == 200 and 
                 call_type in ['load', 'update']) or
            (response.status_code == 201 and call_type == 'create')):
                msg = "call_type: %s successfully completed" % call_type
                log.info(msg)
                return self.to_instance(response)
            elif (response.status_code == 200 and call_type in ['delete', 'destroy']):
            #delete success
                msg ="call_type: %s successfully completed" % call_type
                log.info(msg)
                return self._try_to_serialize(response)
            elif 200 <= response.status_code <= 299:
                return self._try_to_serialize(response)
        except Exception as e:
            msg = "Exception occoured %s url: %s" % (e, url)
            log.error(msg)
            raise e
1350100
def _build_request(self, method, url, params=None):
        
        full_params = self._get_base_params()
        if params is not None:
            full_params.update(params)
        try:
            request_func = lambda u, d: \
                getattr(self._connector, method.lower())(u, params=d,
                    headers=self._request_headers)
        except AttributeError:
            raise ApiException('Invalid request method')
        # TODO: need to catch a network here and raise as ApiNetworkException

        def do_request():
            logger.debug('Sending %s request "%s" with params: %r',
                method, url, full_params)
            try:
                resp = request_func(url, full_params)
                logger.debug('Received response code: %d', resp.status_code)
            except requests.RequestException as err:
                raise ApiNetworkException(err)

            try:
                resp_json = resp.json()
            except TypeError:
                resp_json = resp.json

            method_returns_list = False
            try:
                resp_json['error']
            except TypeError:
                logger.warn('Api method did not return map: %s', method)
                method_returns_list = True
            except KeyError:
                logger.warn('Api method did not return map with error key: %s', method)

            if method_returns_list is None:
                raise ApiBadResponseException(resp.content)
            elif method_returns_list:
                data = resp_json
            else:
                try:
                    if resp_json['error']:
                        raise ApiError('%s: %s' % (resp_json['code'], resp_json['message']))
                except KeyError:
                    data = resp_json
                else:
                    data = resp_json['data']
                    self._do_post_request_tasks(data)
            self._last_response = resp
            return data
        return do_request
1333871
def api_request(*args, **kwargs):
        
        r = requests.request(*args, **kwargs)
        return APIResponse(r)
530452
def dispatch(self, request, *args, **kwargs):
        
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
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)
164763
def call(self, callname, arguments=None):
        """"""
        # See if a method override exists
        action = getattr(self.api, callname, None)
        if action is None:
            try:
                action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
            except AttributeError:
                action = callname

        if not callable(action):
            request = self._generate_request(action, arguments)
            if action is None:
                return self._generate_result(
                    callname, self.api.call(*call_args(callname, arguments)))
            return self._generate_result(
                callname, self.api.call(*call_args(action, arguments)))

        request = self._generate_request(callname, arguments)
        return self._generate_result(callname, action(request))
572395
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    /**
     * Parse the body of the request as a JSON object and return it.
     */
    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body ? JSON.parse(opts.body) : opts.body;
        },
    });

    /**
     * Return the raw body passed to request
     */
    Object.defineProperty(this, 'rawData', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}
654862
private void callHandleMethod(Method method, Object instance, ApiZone apiZone,
            Object userAgent) {
        ReflectMethodUtil.invokeHandleMethod(method, instance, context, apiZone, userAgent);
    }