Hello, I have the following python code block. Unfortunately, it only returns 1000 out of 78K possible results. Not sure what I’m missing since I’m taking into account both pagination and rate limit of 100 calls / 10 seconds. Any help is appreciated.
import requestsimport jsonimport pandas as pdimport timedef flatten_json(y):out = {}def flatten(x, name=''):if type(x) is dict:for a in x:flatten(x[a], name + a + '_')elif type(x) is list:i = 0for a in x:flatten(a, name + str(i) + '_')i += 1else:out[name[:-1]] = xflatten(y)return out# Bearer token for authenticationbearer_token = "pretend_token"# Base URL for searching contactsbase_url = "https://api.hubapi.com/crm/v3/objects/contacts/search"# Headers with Bearer token for authenticationheaders = {'Authorization': f'Bearer {bearer_token}','Content-Type': 'application/json'}# Initialize variables for pagination and rate limitingall_contacts = []after = 0limit = 100has_more = Truestart_time = time.time()request_count = 0MAX_REQUESTS = 15 # Max requests per windowWINDOW_SIZE = 10 # Window size in secondswhile has_more:current_time = time.time()elapsed_time = current_time - start_time# Check for rate limitingif elapsed_time > WINDOW_SIZE:start_time = current_timerequest_count = 0elif request_count >= MAX_REQUESTS:time.sleep(WINDOW_SIZE - elapsed_time)start_time = time.time()request_count = 0# Request body with filters and paginationpayload = json.dumps({"filterGroups": [{"filters": [{"propertyName": "example_prop name","operator": "EQ","value": "true"}]}],"limit": limit,"after": after})try:# POST request to search contacts with paginationresponse = requests.request("POST", base_url, headers=headers, data=payload)data = response.json()# Check if 'results' key is in responseif 'results' in data:# Flatten and extend the resultsflat_data = [flatten_json(item) for item in data['results']]all_contacts.extend(flat_data)# Update 'after' for next paginationif 'paging' in data and 'next' in data['paging']:after = data['paging']['next']['after']else:has_more = Falseelse:print("No 'results' key found in the response.")breakexcept requests.exceptions.RequestException as e:print(f"Request failed: {e}")breakrequest_count += 1# Convert all flattened results to a DataFramecontacts_df = pd.DataFrame(all_contacts)# Print the DataFrameprint(contacts_df)
