Skip to content

Commit

Permalink
Abstract away request logic
Browse files Browse the repository at this point in the history
  • Loading branch information
edgarrmondragon committed Sep 21, 2023
1 parent 6ce6894 commit 1a7ebac
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions src/citric/rest/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,34 @@ def _auth(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
request.headers["Authorization"] = f"Bearer {self.__session_id}"
return request

def make_request(
self,
method: str,
path: str,
*,
params: t.Mapping[str, t.Any] | None = None,
json: t.Any | None = None, # noqa: ANN401
) -> requests.Response:
"""Make a request to the REST API.
Args:
method: HTTP method.
path: URL path.
params: Query parameters.
json: JSON data.
Returns:
Response.
"""
response = self._session.request(
method=method,
url=f"{self.url}{path}",
params=params,
json=json,
)
response.raise_for_status()
return response

def __enter__(self: Self) -> Self:
"""Context manager for REST session.
Expand Down Expand Up @@ -124,8 +152,7 @@ def get_surveys(self) -> list[dict[str, t.Any]]:
Returns:
List of surveys.
"""
response = self._session.get(url=f"{self.url}/rest/v1/survey")
response.raise_for_status()
response = self._make_request("GET", "/rest/v1/survey")
return response.json()["surveys"]

def get_survey_details(self, survey_id: int) -> dict[str, t.Any]:
Expand All @@ -137,8 +164,7 @@ def get_survey_details(self, survey_id: int) -> dict[str, t.Any]:
Returns:
Survey details.
"""
response = self._session.get(f"{self.url}/rest/v1/survey-detail/{survey_id}")
response.raise_for_status()
response = self._make_request("GET", f"/rest/v1/survey-detail/{survey_id}")
return response.json()["survey"]

def update_survey_details(
Expand All @@ -155,8 +181,9 @@ def update_survey_details(
Returns:
Updated survey details.
"""
response = self._session.patch(
f"{self.url}/rest/v1/survey-detail/{survey_id}",
response = self._make_request(
"PATCH",
f"/rest/v1/survey-detail/{survey_id}",
json={
"patch": [
{
Expand All @@ -168,5 +195,4 @@ def update_survey_details(
],
},
)
response.raise_for_status()
return response.json()

0 comments on commit 1a7ebac

Please sign in to comment.