From 80f8608340b837cdc166d9867d8e01d1f4c546ad Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Thu, 7 Sep 2023 21:07:31 -0500 Subject: [PATCH] Add web API methods for fetching donations from NationBuilder --- rattail_nationbuilder/nationbuilder/webapi.py | 68 ++++++++++++++++++- 1 file changed, 66 insertions(+), 2 deletions(-) diff --git a/rattail_nationbuilder/nationbuilder/webapi.py b/rattail_nationbuilder/nationbuilder/webapi.py index 936315b..9518e46 100644 --- a/rattail_nationbuilder/nationbuilder/webapi.py +++ b/rattail_nationbuilder/nationbuilder/webapi.py @@ -24,9 +24,14 @@ NationBuilder Web API """ +import logging + import requests +log = logging.getLogger(__name__) + + class NationBuilderWebAPI(object): """ Simple web API for NationBuilder. @@ -84,7 +89,7 @@ class NationBuilderWebAPI(object): """ return self._request('GET', api_method, params=params) - def get_people(self, page_size=100, progress=None, **kwargs): + def get_people(self, page_size=10, progress=None, **kwargs): """ Retrieve all Person records. @@ -109,7 +114,7 @@ class NationBuilderWebAPI(object): message="Fetching Person data from NationBuilder") return people - def get_people_with_tag(self, tag, page_size=100, max_pages=None, **kwargs): + def get_people_with_tag(self, tag, page_size=10, max_pages=None, **kwargs): """ Retrieve all Person records with the given tag. @@ -135,3 +140,62 @@ class NationBuilderWebAPI(object): pages += 1 return people + + def get_donations(self, page_size=10, max_pages=None, **kwargs): + """ + Retrieve all Donation records. + + https://apiexplorer.nationbuilder.com/nationbuilder#Donations + """ + donations = [] + + # get first page + url = f'/api/v1/donations?limit={page_size}' + response = self.get(url) + data = response.json() + donations.extend(data['results']) + pages = 1 + + # get more pages, until complete + while data['next']: + if max_pages and pages >= max_pages: + break + response = self.get(data['next']) + data = response.json() + donations.extend(data['results']) + pages += 1 + log.debug("have fetched %s pages", pages) + + return donations + + def search_donations(self, page_size=10, max_pages=None, **kwargs): + """ + Search for matching Donation records. + + https://apiexplorer.nationbuilder.com/nationbuilder#Donations + """ + donations = [] + + # get first page + url = f'/api/v1/donations/search?limit={page_size}' + for field in ('created_since', 'succeeded_since', 'failed_since'): + value = kwargs.get(field) + if value: + value = value.strftime('%Y-%m-%dT%H:%M:%S%z') + url += f"&{field}={value}" + response = self.get(url) + data = response.json() + donations.extend(data['results']) + pages = 1 + + # get more pages, until complete + while data['next']: + if max_pages and pages >= max_pages: + break + response = self.get(data['next']) + data = response.json() + donations.extend(data['results']) + pages += 1 + log.debug("have fetched %s pages", pages) + + return donations