diff options
| author | 2019-12-21 11:27:00 -0800 | |
|---|---|---|
| committer | 2020-02-12 10:07:44 -0800 | |
| commit | d3bc9a978e2ff348ff33dfef26f430d59b89695f (patch) | |
| tree | 50b8c0b4db3b8750db6fdb912ed5fa3fb9f1bc89 | |
| parent | API: define functions with keyword-only arguments (diff) | |
API: create request function which has a param for the HTTP method
Reduces code redundancy.
| -rw-r--r-- | bot/api.py | 28 |
1 files changed, 10 insertions, 18 deletions
diff --git a/bot/api.py b/bot/api.py index 992499809..a9d2baa4d 100644 --- a/bot/api.py +++ b/bot/api.py @@ -85,37 +85,29 @@ class APIClient: response_text = await response.text() raise ResponseCodeError(response=response, response_text=response_text) - async def get(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: - """Site API GET.""" + async def request(self, method: str, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: + """Send an HTTP request to the site API and return the JSON response.""" await self._ready.wait() - async with self.session.get(self._url_for(endpoint), **kwargs) as resp: + async with self.session.request(method.upper(), self._url_for(endpoint), **kwargs) as resp: await self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() + async def get(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: + """Site API GET.""" + return await self.request("GET", endpoint, raise_for_status=raise_for_status, **kwargs) + async def patch(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: """Site API PATCH.""" - await self._ready.wait() - - async with self.session.patch(self._url_for(endpoint), **kwargs) as resp: - await self.maybe_raise_for_status(resp, raise_for_status) - return await resp.json() + return await self.request("PATCH", endpoint, raise_for_status=raise_for_status, **kwargs) async def post(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: """Site API POST.""" - await self._ready.wait() - - async with self.session.post(self._url_for(endpoint), **kwargs) as resp: - await self.maybe_raise_for_status(resp, raise_for_status) - return await resp.json() + return await self.request("POST", endpoint, raise_for_status=raise_for_status, **kwargs) async def put(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> dict: """Site API PUT.""" - await self._ready.wait() - - async with self.session.put(self._url_for(endpoint), **kwargs) as resp: - await self.maybe_raise_for_status(resp, raise_for_status) - return await resp.json() + return await self.request("PUT", endpoint, raise_for_status=raise_for_status, **kwargs) async def delete(self, endpoint: str, *, raise_for_status: bool = True, **kwargs) -> Optional[dict]: """Site API DELETE.""" |