Use this decorator to expose API endpoints on your API classes.

        :param url:
            Relative URL for the endpoint
        :param methods:
            Allowed HTTP methods. By default only GET is allowed.
515775
def expose(url="/", methods=("GET",)):
    

    def wrap(f):
        if not hasattr(f, "_urls"):
            f._urls = []
        f._urls.append((url, methods))
        return f

    return wrap
1233763
def _request(self, url, params=None):
        

        response = get(url, params=params, headers=self.headers, timeout=30)

        if response.status_code != 200:
            raise APIError('Request to {} returned {}'.format(response.url, response.status_code))

        response = response.json()

        error_text = response['service_meta']['error_text']
        if error_text:
            raise APIError(error_text)

        return response
1123399
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
        
        if not self.token:
            raise RuntimeError("You do not have an API token!")

        if not method:
            raise ValueError("Method is required for API calls!")

        if model:
            endpoint = endpoint.format(**vars(model))
        url = '{}{}'.format(self.base_url, endpoint)
        headers = {
            'Authorization': "Bearer {}".format(self.token),
            'Content-Type': 'application/json',
            'User-Agent': self._user_agent,
        }

        if filters:
            headers['X-Filter'] = json.dumps(filters)

        body = None
        if data is not None:
            body = json.dumps(data)

        response = method(url, headers=headers, data=body)

        warning = response.headers.get('Warning', None)
        if warning:
            logger.warning('Received warning from server: {}'.format(warning))

        if 399 < response.status_code < 600:
            j = None
            error_msg = '{}: '.format(response.status_code)
            try:
                j = response.json()
                if 'errors' in j.keys():
                    for e in j['errors']:
                        error_msg += '{}; '.format(e['reason']) \
                                if 'reason' in e.keys() else ''
            except:
                pass
            raise ApiError(error_msg, status=response.status_code, json=j)

        if response.status_code != 204:
            j = response.json()
        else:
            j = None # handle no response body

        return j
651228
def _api_get(self, url, **kwargs):
        
        kwargs['url'] = self.url + url
        kwargs['auth'] = self.auth

        headers = deepcopy(self.headers)
        headers.update(kwargs.get('headers', {}))
        kwargs['headers'] = headers
        return self._get(**kwargs)
1246187
def expose_endpoints (module, *args):
    
    
    for op in args:
        # Capture the closure state
        def create_method (o):
            return lambda exp: send_request(o, exp)
        
        setattr(sys.modules[__name__], op, create_method(op))
        setattr(module, op, getattr(sys.modules[__name__], op))
484621
def get(self, endpoint, *args, **kwargs):
        
        endpoint = self.base_url + endpoint
        return self._make_request(endpoint, type='GET')
919365
def make_api_call(self, method, url, json_params=None):
        

        url = self.BRANCH_BASE_URI+url

        if self.verbose is True:
            print("Making web request: {}".format(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("Params: {}".format(encoded_params))

        request = Request(url, encoded_params.encode('utf-8'), headers)
        request.get_method = lambda: method
        response = urlopen(request).read()
        return json.loads(response.decode('utf-8'))
78097
def require_http_methods(request_methods):
    
    if not isinstance(request_methods, (list, tuple)):
        raise ImproperlyConfigured(
            "require_http_methods decorator must be called "
            "with a list or tuple of strings. For example:\n\n"
            "    @require_http_methods(['GET', 'POST'])\n"
            "    def function_view(request):\n"
            "        ...\n")

    request_methods = list(map(str.upper, request_methods))

    for method in request_methods:
        if method not in HTTP_METHOD_NAMES:
            raise ImproperlyConfigured(
                "require_http_method called with '%s', "
                "which is not a valid HTTP method.\n"
                % (method,))

    if 'GET' in request_methods and 'HEAD' not in request_methods:
        request_methods.append('HEAD')
    if 'OPTIONS' not in request_methods:
        request_methods.append('OPTIONS')
    request_methods.sort()

    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method == 'OPTIONS':
                response = HttpResponse()
                response['Allow'] = ', '.join(
                    [m.upper() for m in request_methods])
                response['Content-Length'] = '0'
                return response
            if request.method not in request_methods:
                logger.warning(
                    'Method Not Allowed (%s): %s',
                    request.method,
                    request.path,
                    extra={
                        'status_code': 405,
                        'request': request
                    }
                )
                return HttpResponseNotAllowed(request_methods)
            return func(request, *args, **kwargs)
        return inner
    return decorator
925995
def request(http_method, data={}, url="")
      final_url = @options[:base_url] << url
        begin
          case http_method
              when :get
                response = Curl.get(final_url, data) do |http|
                  http.headers['x-api-key'] = @options[:api_key]
                  http.headers['Accept'] = 'application/json'
                end
          end
        rescue Curl::Err::HostResolutionError
          raise Fulfil::HostResolutionError, "Invalid Subdomain"
        end
      parse_response response
    end
1327770
def wrap_handler(self, api_types, methods, endpoints):
        

        def wrapper(fn):
            @wraps(fn)
            def wrapped(*args, **kwargs):
                return fn(*args, **kwargs)

            for api_type in api_types:
                for method in methods:
                    for endpoint in endpoints:
                        key = (api_type, method, endpoint)
                        self._handler_chains.setdefault(key, [])
                        self._handler_chains[key].append(wrapped)
            return wrapped

        return wrapper
353183
def add_params(endpoint, params):
    
    p = PreparedRequest()
    p.prepare(url=endpoint, params=params)
    if PY2:  # pragma: no cover
        return unicode(p.url)
    else:  # pragma: no cover
        return p.url
1332881
def request(cls, method, url, **kwargs):
		
		methodupper = method.upper()
		hasdata = 'data' in kwargs
		if methodupper == 'GET':
			if hasdata:
				print("ERROR: Can't do HTTP GET when the 'data' parameter presents")
				assert False
			resp = ulr.urlopen(url, **kwargs)
		elif methodupper == 'POST':
			if hasdata:
				resp = ulr.urlopen(url, **kwargs)
			else:
				resp = ulr.urlopen(url, data = '', **kwargs)
		else:
			raise NotImplementedError()

		return resp
635834
def _method_url(self, method_name):
        
        return "{base_url}/api/{api}/{method}".format(
            base_url=self._base_url(),
            api=self.api_version,
            method=method_name
        )
1202475
def _request(self, url, **kwargs):
        '''
        '''
        if self.method is None:
            raise NotImplementedError('method must be defined on a subclass')
        response = requests.request(self.method, url, **kwargs)
        return self.response_class(response, sender=self)
233804
def http_methods(self, urls=None, **route_data):
        """"""
        def decorator(class_definition):
            instance = class_definition
            if isinstance(class_definition, type):
                instance = class_definition()

            router = self.urls(urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data)
            for method in HTTP_METHODS:
                handler = getattr(instance, method.lower(), None)
                if handler:
                    http_routes = getattr(handler, '_hug_http_routes', ())
                    if http_routes:
                        for route in http_routes:
                            http(**router.accept(method).where(**route).route)(handler)
                    else:
                        http(**router.accept(method).route)(handler)

                    cli_routes = getattr(handler, '_hug_cli_routes', ())
                    if cli_routes:
                        for route in cli_routes:
                            cli(**self.where(**route).route)(handler)
            return class_definition
        return decorator
1312673
def request(method:, url_path:, body: nil, params: {}, header_overrides: {})
      spec = body.nil? ? {} : {body_type: :json}
      endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec)
      request_spec = Smartsheet::API::RequestSpec.new(
          header_overrides: header_overrides,
          body: body,
          params: params
      )
      client.make_request(endpoint_spec, request_spec)
    end
989270
function API(method, url, data, callback) {
    if (typeof callback === 'undefined') {
        callback  = data;
        data  = {};
    }

    url             = this.prepareUrl(url);
    this.callback   = callback || noop;
    this.data       = data;

    this.options          = extend({}, requestOptions);
    this.options.encoding = this.options.encoding || 'utf-8';

    // these particular set of options should be immutable
    this.options.method         = method;
    this.options.uri            = url;
    this.options.followRedirect = false;

    this[method.toLowerCase()]();

    return this;
}