diff --git a/pyDataverse/api.py b/pyDataverse/api.py index 1ce6c38..8cce5a8 100644 --- a/pyDataverse/api.py +++ b/pyDataverse/api.py @@ -411,9 +411,14 @@ def _sync_request( kwargs = self._filter_kwargs(kwargs) try: - resp = method(**kwargs, auth=self.auth, follow_redirects=True, timeout=None) + resp: httpx.Response = method( + **kwargs, auth=self.auth, follow_redirects=True, timeout=None + ) if resp.status_code == 401: - error_msg = resp.json()["message"] + try: + error_msg = resp.json()["message"] + except json.JSONDecodeError: + error_msg = resp.reason_phrase raise ApiAuthorizationError( "ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format( kwargs["url"], error_msg diff --git a/tests/api/test_api.py b/tests/api/test_api.py index c8e7b72..817c4b3 100644 --- a/tests/api/test_api.py +++ b/tests/api/test_api.py @@ -217,3 +217,16 @@ def test_sword_api_requires_http_basic_auth(self): API_TOKEN = os.getenv("API_TOKEN") api = SwordApi(BASE_URL, api_token=API_TOKEN) assert isinstance(api.auth, httpx.BasicAuth) + + def test_sword_api_can_authenticate(self): + BASE_URL = os.getenv("BASE_URL") + API_TOKEN = os.getenv("API_TOKEN") + api = SwordApi(BASE_URL, api_token=API_TOKEN) + response = api.get_service_document() + assert response.status_code == 200 + + def test_sword_api_cannot_authenticate_without_token(self): + BASE_URL = os.getenv("BASE_URL") + api = SwordApi(BASE_URL) + with pytest.raises(ApiAuthorizationError): + api.get_service_document()