Skip to content

Instantly share code, notes, and snippets.

@lucidfrontier45
Created April 22, 2020 00:39
Show Gist options
  • Save lucidfrontier45/73c5661c0bc970f416ed7e93fe1d2cf3 to your computer and use it in GitHub Desktop.
Save lucidfrontier45/73c5661c0bc970f416ed7e93fe1d2cf3 to your computer and use it in GitHub Desktop.
APIClient wrapper
from urllib.parse import urljoin
import requests
def ensure_slash(s):
if not s.endswith("/"):
s = s + "/"
return s
class APIClient:
def __init__(self, base_url: str, **headers):
self._base_url = ensure_slash(base_url)
self._headers = headers
def request(self, method, path, **kwargs):
url = urljoin(self._base_url, path)
with requests.Session() as session:
session.headers.update(self._headers)
return session.request(method=method, url=url, **kwargs)
def get(self, path, params=None, **kwargs):
kwargs.setdefault("allow_redirects", True)
return self.request("get", path, params=params, **kwargs)
def options(self, path, **kwargs):
kwargs.setdefault("allow_redirects", True)
return self.request("options", path, **kwargs)
def head(self, path, **kwargs):
kwargs.setdefault("allow_redirects", False)
return self.request("head", path, **kwargs)
def post(self, path, data=None, json=None, **kwargs):
return self.request("post", path, data=data, json=json, **kwargs)
def put(self, path, data=None, **kwargs):
return self.request("put", path, data=data, **kwargs)
def patch(self, path, data=None, **kwargs):
return self.request("patch", path, data=data, **kwargs)
def delete(self, path, **kwargs):
return self.request("delete", path, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment