Glances API RESTful implementation.

        Return the help data or 404 error.
776445
def _api_help(self):
        
        response.content_type = 'application/json; charset=utf-8'

        # Update the stat
        view_data = self.stats.get_plugin("help").get_view_data()
        try:
            plist = json.dumps(view_data, sort_keys=True)
        except Exception as e:
            abort(404, "Cannot get help view data (%s)" % str(e))
        return plist
1032218
def api_related(self, query):
        '''
        
        '''

        url = "{0}/{1}/related/?format=json".format(self.base_url, query)
        response = requests.get(url, headers=self.headers, verify=self.verify_ssl)

        if response.status_code == 200:
            return response.json()
        else:
            self.error('Received status code: {0} from Soltra Server. Content:\n{1}'.format(
                response.status_code, response.text)
            )
80106
def check_server(self):
        
        msg = 'API server not found. Please check your API url configuration.'

        try:
            response = self.session.head(self.domain)
        except Exception as e:
            raise_from(errors.ServerError(msg), e)

        try:
            self._check_response(response)
        except errors.NotFound as e:
            raise raise_from(errors.ServerError(msg), e)
5400
def get_error(exc):
    

    if isinstance(exc, HTTPError):
        # Returning the HTTP Error code coming from requests module
        return exc.response.status_code, text(exc.response.content)

    if isinstance(exc, Timeout):
        # A timeout is a 408, and it's not a HTTPError (why? dunno).
        return 408, exc

    if isinstance(exc, Http404):
        # 404 is 404
        return 404, exc

    if isinstance(exc, PermissionDenied):
        # Permission denied is 403
        return 403, exc

    if isinstance(exc, SuspiciousOperation):
        # Shouldn't happen, but you never know
        return 400, exc

    # The default error code is 500
    return 500, exc
1339090
function(resource) {
    // If API discovery had any failures, calls to api info should redirect to the error page
    if (APIS_CFG.API_DISCOVERY_ERRORS) {
      var possibleCertFailure  = _.every(APIS_CFG.API_DISCOVERY_ERRORS, function(error){
        return _.get(error, "data.status") === 0;
      });
      if (possibleCertFailure && !AuthService.isLoggedIn()) {
        // will trigger a login flow which will redirect to the api server
        AuthService.withUser();
        return;
      }
      var fatal = false;
      _.each(APIS_CFG.API_DISCOVERY_ERRORS, function(discoveryError) {
        if (discoveryError.fatal) {
          Logger.error('API discovery failed (fatal error)', discoveryError);
          fatal = true;
          return;
        }

        Logger.warn('API discovery failed', discoveryError);
      });
      if (fatal) {
        // Go to the error page on fatal errors, the server might be down.
        // Can't use Navigate.toErrorPage or it will create a circular
        // dependency
        $window.location.href = URI('error').query({
          error_description: "Unable to load details about the server. If the problem continues, please contact your system administrator.",
          error: "API_DISCOVERY"
        }).toString();
        return;
      }
    }

    resource = toResourceGroupVersion(resource);
    var primaryResource = resource.primaryResource();
    var discoveredResource;
    // API info for resources in an API group, if the resource was not found during discovery return undefined
    if (resource.group) {
      discoveredResource = _.get(APIS_CFG, ["groups", resource.group, "versions", resource.version, "resources", primaryResource]);
      if (!discoveredResource) {
        return undefined;
      }
      var hostPrefixObj = _.get(APIS_CFG, ["groups", resource.group, 'hostPrefix']) || APIS_CFG;
      return {
        resource: resource.resource,
        group:    resource.group,
        version:  resource.version,
        protocol: hostPrefixObj.protocol,
        hostPort: hostPrefixObj.hostPort,
        prefix:   hostPrefixObj.prefix,
        namespaced: discoveredResource.namespaced,
        verbs: discoveredResource.verbs
      };
    }

    // Resources without an API group could be legacy k8s or origin resources.
    // Scan through resources to determine which this is.
    var api;
    for (var apiName in API_CFG) {
      api = API_CFG[apiName];
      discoveredResource = _.get(api, ["resources", resource.version, primaryResource]);
      if (!discoveredResource) {
        continue;
      }
      return {
        resource: resource.resource,
        version:  resource.version,
        hostPort: api.hostPort,
        prefix:   api.prefix,
        namespaced: discoveredResource.namespaced,
        verbs: discoveredResource.verbs
      };
    }
    return undefined;
  }
568049
def _is_valid_api_url(self, url):
        """"""
        # Check response is a JSON with ok: 1
        data = {}
        try:
            r = requests.get(url, proxies=self.proxy_servers)
            content = to_text_string(r.content, encoding='utf-8')
            data = json.loads(content)
        except Exception as error:
            logger.error(str(error))

        return data.get('ok', 0) == 1
569374
def read_resp_data(service_name, implementation_name, url, response):
    
    RR = _mockdata_path_root(service_name, implementation_name)
    for resource_dir in app_resource_dirs:
        path = os.path.join(resource_dir['path'],
                            service_name,
                            implementation_name)
        found_header = _read_resp_header(path, url, response)
        found_body = _read_resp_body(path, url, response)
        if found_body or found_header:
            return response
    response.status = 404
    return response
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)}
708803
def check_api_error(api_response):
    print(api_response)
    """"""
    if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200:
            print("Server response code: %s" % api_response['code'])
            print("Server response: %s" % api_response)
            raise exceptions.HTTPError('Unexpected response', response=api_response)
    if type(api_response) == dict and (api_response.get('status') == 'failed'):
        if 'ProgrammingError' in api_response.get('exception_cls'):
            raise DatabaseError(message='PyBossa database error.',
                                error=api_response)
        if ('DBIntegrityError' in api_response.get('exception_cls') and
            'project' in api_response.get('target')):
            msg = 'PyBossa project already exists.'
            raise ProjectAlreadyExists(message=msg, error=api_response)
        if 'project' in api_response.get('target'):
            raise ProjectNotFound(message='PyBossa Project not found',
                                  error=api_response)
        if 'task' in api_response.get('target'):
            raise TaskNotFound(message='PyBossa Task not found',
                               error=api_response)
        else:
            print("Server response: %s" % api_response)
            raise exceptions.HTTPError('Unexpected response', response=api_response)
1326725
def get(self, res_path, timeout=10.):
	
		
		
		resp = requests.get(
			self.__res_uri(res_path),
			headers=self.__headers(),
			verify=False,
			auth=self.__auth(),
			timeout=timeout
		)
		return (
			resp.status_code,
			json.loads(resp.text) if resp.status_code == 200 else {}
		)
94880
def _get(self, url):
        """"""
        req = requests.get(RequestHandler.BASE_URL + url, headers=self.headers)
        status_code = req.status_code
        if status_code == requests.codes.ok:
            return req
        elif status_code == requests.codes.bad:
            raise APIErrorException('Invalid request. Check parameters.')
        elif status_code == requests.codes.forbidden:
            raise APIErrorException('This resource is restricted')
        elif status_code == requests.codes.not_found:
            raise APIErrorException('This resource does not exist. Check parameters')
        elif status_code == requests.codes.too_many_requests:
            raise APIErrorException('You have exceeded your allowed requests per minute/day')
128816
def api_version(self, verbose=False):
        '''
        
        '''
        return self.__auth_req_get(self.rest_url, verbose=verbose)
624127
function (req, res) {
        var id = req.params.id;
        {modelName}.findOne({_id: id}, function (err, {name}) {
            if (err) {
                return res.status(500).json({
                    message: 'Error when getting {name}.',
                    error: err
                });
            }
            if (!{name}) {
                return res.status(404).json({
                    message: 'No such {name}'
                });
            }
            return res.json({name});
        });
    }
70264
def rest_get(url, timeout, show_error=False):
    ''''''
    try:
        response = requests.get(url, timeout=timeout)
        return response
    except Exception as exception:
        if show_error:
            print_error(exception)
        return None
718271
def error(self, status_code, request, message=None):
        
        status_code_text = HTTP_STATUS_CODES.get(status_code, 'http error')
        status_error_tag = status_code_text.lower().replace(' ', '_')
        custom_response_map = {
            404: self.make_error_response(
                status_error_tag,
                'The requested URL {} was not found on this service.'.format(
                    request.path
                )
            ),
            400: self.make_error_response(status_error_tag, message),
            405: self.make_error_response(
                status_error_tag,
                'The requested URL {} was not allowed HTTP method {}.'.format(
                    request.path, request.method
                )
            ),
        }
        return self._raw_response(
            status_code,
            custom_response_map.get(
                status_code,
                self.make_error_response(
                    status_error_tag, message or status_code_text
                )
            )
        )
497173
def get_request_data():
    
    request = get_request()
    data = request.get("BODY", "{}")
    if not is_json_deserializable(data):
        from plone.jsonapi.routes.exceptions import APIError
        raise APIError(400, "Request Data is not JSON deserializable – Check JSON Syntax!")
    return _.convert(json.loads(data), _.to_list)
1052795
def _get_error_message(response):
    """"""
    try:
        data = response.json()
        if "error_description" in data:
            return data['error_description']
        if "error" in data:
            return data['error']
    except Exception:
        pass

    return "Unknown error"