Skip to content

Commit

Permalink
api: Add general method to make requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
fishinthecalculator committed Jun 12, 2024
1 parent 978c574 commit 58c00bc
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions pyactionnetwork/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,29 @@ def __init__(self, api_key, **kwargs):
self.base_url = self.config.get('links', {}).get('self', 'https://actionnetwork.org/api/v2/')
print(self.config['motd'])

def request(self, verb, url, json=None):
kwargs = {
"headers": self.headers,
"url": url
}
if json:
kwargs.update({"json": json})
return requests.request(
verb,
**kwargs
)

def request_json(self, verb, url, json=None, quiet=False):
if not quiet:
logger.debug(f"{verb} {url} {json}")
r = self.request(verb, url, json=json)
if not quiet:
logger.debug(f"{r.status_code} {r.headers['content-type']} {r.text}")
return r.json()

def refresh_config(self):
"""Get a new version of the base_url config."""
self.config = requests.get(url="https://actionnetwork.org/api/v2/",
headers=self.headers).json()
self.config = self.request_json("GET", url="https://actionnetwork.org/api/v2/")

def resource_to_url(self, resource):
"""Convert a named endpoint into a URL.
Expand Down Expand Up @@ -46,7 +65,7 @@ def get_resource(self, resource):
(dict) API response from endpoint or `None` if not found/valid.
"""
url = self.resource_to_url(resource)
return requests.get(url, headers=self.headers).json()
return self.request_json("GET", url=url)

def get_person(self, person_id=None, search_by='email', search_string=None):
"""Search for a user.
Expand All @@ -68,8 +87,7 @@ def get_person(self, person_id=None, search_by='email', search_string=None):
search_by,
quote(search_string))

resp = requests.get(url, headers=self.headers)
return resp.json()
return self.request_json("GET", url=url)

def create_person(self,
email=None,
Expand Down Expand Up @@ -132,8 +150,7 @@ def create_person(self,
'add_tags': list(tags)
}

resp = requests.post(url, json=payload, headers=self.headers)
return resp.json()
return self.request_json("POST", url=url, json=payload)

def update_person(self,
person_id=None,
Expand Down Expand Up @@ -192,8 +209,7 @@ def update_person(self,
'custom_fields': custom_fields,
}

resp = requests.put(url, json=payload, headers=self.headers)
return resp.json()
return self.request_json("PUT", url=url, json=payload)

def search(self, resource, operator, term):
"""Search for a given `term` within a `resource`.
Expand Down

0 comments on commit 58c00bc

Please sign in to comment.