Make an API call to iNaturalist.

    endpoint is a string such as 'observations' !! do not put / in front
    method: 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'
    kwargs are passed to requests.request
    Returns a requests.Response object
334557
def make_inaturalist_api_get_call(endpoint: str, params: Dict, **kwargs) -> requests.Response:
    
    headers = {'Accept': 'application/json'}

    response = requests.get(urljoin(INAT_NODE_API_BASE_URL, endpoint), params, headers=headers, **kwargs)
    return response
271272
def delete(self, endpoint, json=None, params=None, **kwargs):
        
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('delete', endpoint, data=json, params=params)
1139827
def _post(url:str, params:dict, headers:dict) -> dict:
    
    response = requests.post(url, params=params, headers=headers)
    data = response.json()
    if response.status_code != 200 or "error" in data:
        raise GoogleApiError({"status_code": response.status_code,
                                  "error": data.get("error", "")})
    return data
548907
def _api_handler(self, *args, **kwargs):
        
        keyword_arguments = {}
        keyword_arguments.update(self.keywords)
        keyword_arguments.update(kwargs)
        return api_handler(*args, **keyword_arguments)
572932
def perform_api_request(
        self,
        url,
        method='POST',
        headers=None,
        body=None,
        **kwargs
    ):
        '''
        
        '''
        assert method in ('GET', 'POST')
        if method == 'GET':
            response = self._perform_get(url, headers=headers, **kwargs)
        elif method == 'POST':
            response = self._perform_post(url, headers=headers, data=body, **kwargs)
        return response
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()
647173
def request(self, method, url, **kwargs):
        

        if "data" in kwargs:
            kwargs["data"] = json.dumps(kwargs["data"])

        kwargs["headers"] = {
            'Content-Type': 'application/json',
            'Authorization': 'token %s' % self.__token__,
        }
        req = make_request(
            method,
            url,
            **kwargs
        )
        self.logger.debug(
            "Request::{}::{}".format(method, url),
            extra={
                "request": kwargs,
                "response": {"headers": req.headers, "code": req.status_code, "data": req.content}
            }
        )
        return req
856833
def _request(method, url, session=None, **kwargs):
    
    url = BASE_URL + url

    if session:
        request_func = getattr(session, method)
    else:
        request_func = getattr(requests, method)
    response = request_func(url, **kwargs)
    # raise an exception if request is not successful
    if not response.status_code == requests.codes.ok:
        raise DweepyError('HTTP {0} response'.format(response.status_code))
    response_json = response.json()
    if response_json['this'] == 'failed':
        raise DweepyError(response_json['because'])
    return response_json['with']
873678
def _put_or_post_json(self, method, url, data):
        
        if self.parsed_endpoint.scheme == 'https':
            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
        else:
            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
        head = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": USER_AGENT,
            API_TOKEN_HEADER_NAME: self.api_token,
        }
        if self.api_version in ['0.1', '0.01a']:
            head[API_VERSION_HEADER_NAME] = self.api_version
        conn.request(method, url, json.dumps(data), head)
        resp = conn.getresponse()
        self._handle_response_errors(method, url, resp)
        return json.loads(resp.read())
287758
def _make_request(self, method, url, post_data=None, body=None):
        
        if not self.connection:
            self._connect()
        try:
            self.connection.close()
        except:
            pass
        self.connection.connect()
        headers = {}
        if self.auth_header:
            headers["Authorization"] = self.auth_header
        self.connection.request(method, url, body, headers)
        resp = self.connection.getresponse()
        return resp
113747
def __request(self, endpoint, method='GET', params=None, convJSON=False):
        
        url = '%s/%s' % (self.api_url, endpoint)

        method = method.lower()
        params = params or {}
        if convJSON:
            params = json.dumps(params)

        func = getattr(self.client, method)
        request_args = {}
        if method == 'get':
            request_args['params'] = params
        else:
            request_args['data'] = params

        try:
            # Normally some valid HTTP-response will be the case
            # if not some exception regarding the request / connection has
            # occurred
            # this will be one of the exceptions of the request module
            # if so, we will a PostcodeError exception and pass the request
            # exception message
            response = func(url, **request_args)
        except requests.RequestException as e:
            raise PostcodeError("ERRrequest", {"exception": e.__doc__})

        content = response.content.decode('utf-8')

        content = json.loads(content)

        if response.status_code == 200:
            return content

        # Errors, otherwise we did not get here ...
        if 'exceptionId' in content:
            raise PostcodeError(content['exceptionId'], content)

        raise PostcodeError("UnknownExceptionFromPostcodeNl")
178754
def _request(self, method, endpoint, id=None, **kwargs):
        ""
        request = getattr(requests, method, None)
        if not callable(request):
            raise RequestError('Invalid method %s' % method)
        # Find files, separate them out to correct kwarg for requests.
        data = kwargs.get('data')
        if data:
            files = {}
            for name, value in list(data.items()):
                # Value might be a file-like object (with a read method), or it
                # might be a (filename, file-like) tuple.
                if hasattr(value, 'read') or isinstance(value, tuple):
                    files[name] = data.pop(name)
            if files:
                kwargs.setdefault('files', {}).update(files)
        path = ['api', self.version, endpoint]
        # If we received an ID, append it to the path.
        if id:
            path.append(str(id))
        # Join fragments into a URL
        path = '/'.join(path)
        if not path.endswith('/'):
            path += '/'
        while '//' in path:
            path = path.replace('//', '/')
        url = self.url + path
        # Add our user agent.
        kwargs.setdefault('headers', {}).setdefault('User-Agent',
                                                    HTTP_USER_AGENT)
        # Now try the request, if we get throttled, sleep and try again.
        trys, retrys = 0, 3
        while True:
            if trys == retrys:
                raise RequestError('Could not complete request after %s trys.'
                                   % trys)
            trys += 1
            try:
                return self._do_request(request, url, **kwargs)
            except ResponseError as e:
                if self.throttle_wait and e.status_code == 503:
                    m = THROTTLE_PATTERN.match(
                        e.response.headers.get('x-throttle', ''))
                    if m:
                        time.sleep(float(m.group(1)))
                        continue
                # Failed for a reason other than throttling.
                raise
647787
def post(self, endpoint, **kwargs):
        
        return self._request(requests.post, endpoint, **kwargs)
593822
def get(cls, api=None, **kwargs):
        
        api = api if api else cls._API
        extra = {
            'resource': cls.__name__,
            'query': {}
        }
        logger.info('Getting resources', extra=extra)
        endpoints = api.get(url=cls._URL['get']).json()
        return Endpoints(api=api, **endpoints)
304891
def get(self, params=None):
        
        return self._call('get', url=self.endpoint, params=params)
892280
def request(self, method, url, data=None, files=None, query=None, headers=None, timeout=60):
        
        headers = headers or {}

        if self.token:
            my_token = self.token
        else:
            from figure import token
            my_token = token

        if my_token:
            self.__set_authorization(headers, my_token)

        METHODS = {
            'get': self.__get,
            'post': self.__post,
            'put': self.__put,
            'head': self.__head,
            'patch': self.__patch
        }
        request_method = METHODS[method.lower()]

        abs_url = urlparse.urljoin(self.api_base, url)

        encoded_query = urllib.urlencode(query or {})

        abs_url = _build_api_url(abs_url, encoded_query)

        try:
            response = request_method(abs_url, data=data, files=files, headers=headers, timeout=timeout)
            response.encoding = 'utf-8'
        except RequestException:
            raise error.APIConnectionError()

        return self._interpret_response(response.text, response.status_code)
586872
def update(self, **args):
        
        self_dict = self.to_dict()
        if args:
            self_dict = dict(list(self_dict.items()) + list(args.items()))
        response = self.requester.put(
            '/{endpoint}/{id}', endpoint=self.endpoint,
            id=self.id, payload=self_dict
        )
        obj_json = response.json()
        if 'version' in obj_json:
            self.__dict__['version'] = obj_json['version']
        return self