class TestApiCalls(unittest.TestCase): @classmethod def setUpClass(self): self.url = os.getenv("url") self.client_id = os.getenv("client_id") self.secret = os.getenv("secret") self.canvas_api = ApiUtil(self.url, self.client_id, self.secret, "canvasreadonly") self.mcommunity_api = ApiUtil(self.url, self.client_id, self.secret, "mcommunity") print ("URL is %s" % self.url) def test_mcommunity(self): uniqname = "uniqname" self.assertEqual(self.mcommunity_api.api_call(f"MCommunity/People/{uniqname}").status_code, 200) def test_pagination(self): resp = self.canvas_api.api_call(f"aa/CanvasReadOnly/courses/1/users") logger.info(resp.headers) def test_canvasreadonly(self): resp = self.canvas_api.api_call(f"aa/CanvasReadOnly/brand_variables") self.assertEqual(resp.status_code, 200)
def api_call_with_retries( api_handler: ApiUtil, url: str, subscription: str, method: str, payload: Union[Dict[str, Any], None] = None, max_req_attempts: int = 3, ) -> Union[Response, None]: """ Pulls data from the UM API Directory, handling errors and retrying if necessary. When the maximum number of request attempts is reached, the function logs an error and returns None. :param api_handler: Instance of ApiUtil :type api_handler: ApiUtil :param url: URL ending for request :type url: string :param subscription: Name of the subscription or scope the request should use :type subscription: string :param method: Request method that should be used (e.g. "GET", "PUT") :type method: string :param payload: Dictionary to include in the request body :type payload: Dictionary with string keys or None, optional :param max_req_attempts: Number of request attempts to make before logging an error :type max_req_attempts: int, optional :return: Either a Response object or None :rtype: Response or None """ if payload is None: request_payload = dict() else: request_payload = payload LOGGER.debug('Making a request for data...') for i in range(1, max_req_attempts + 1): LOGGER.debug(f'Attempt #{i}') response = api_handler.api_call(url, subscription, method, request_payload) LOGGER.debug(f'Response URL: {response.url}') if not check_if_response_successful(response): LOGGER.info('Beginning next_attempt') else: return response LOGGER.error( 'The maximum number of request attempts was reached; returning None') return None