crm api - while loop in Python

Hi Everyone, I a new to APIs and was struggling to get all contacts for CRM API along with properties.

I am able to extract 100 records but was unable to construct a while loop to get all the records. i can see the paging.next.link for another 100 records but unable to loop it. Can anyone please share their loop script to get all the contacts

My code so far

import requests
import json

def contacts(url,headers):
return_data=[]
url=‘https://api.hubapi.com/crm/v3/objects/contacts?limit=100&properties=createdate&properties=work_email&properties=firstname&properties=lastname&properties=mobilephone&properties=phone&properties=website&properties=utm_campaign&properties=utm_content&properties=utm_source&properties=utm_term&properties=company_phone&properties=company_size&properties=contact_source&properties=contact_type&properties=hs_additional_emails&properties=hs_all_contact_vids&properties=hs_analytics_first_touch_converting_campaign&properties=Original+Source&properties=Job+Title&archived=False
headers = {
“Accept”: “application/json”,
“Content-Type”: “application/json”,
‘Authorization’: ‘Bearer xxx-xxx-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx’
}
response = requests.get(url,headers = headers)
data = response.json()
while True:
for result in data[‘results’]:
return_data.append((result[‘id’]))
if data[‘paging’][‘next’][‘link’] is None:
break
response = requests.get(data[‘paging’][‘next’][‘link’])
data = response.json()
return return_data

print(contacts)

can you elaborate what do you mean when you say “unable to loop it”?
In the code above you define a function, but never call it. And you might want to use code blocks to preserve formating.

Hi @SaiR,

Agreed with @ASol, you do define a function but never call it, so you can’t expect the loop to work.

Also, you define your function as follows :

def contacts(url,headers):

But the url and headers are defined within the function without reusing the input variables, which means you can remove them from the function → def contacts() will be enough.

Assuming the rest of the function is ok (and it does look ok), this would work :

import requests 
import json

def contacts():
 return_data=[]
 url="https://api.hubapi.com/crm/v3/objects/contacts? 
 limit=100&properties=createdate&properties=work_email..."
 headers = {
 "Accept": "application/json",
 "Content-Type": "application/json",
 "Authorization": "Bearer xxx-xxx-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
 }

 response = requests.get(url,headers = headers)
 data = response.json()

 while True:
 for result in data['results']:
 return_data.append((result['id']))

 if data['paging']['next']['link'] is None:
 break

 response = requests.get(data['paging']['next']['link'])
 data = response.json()

 return return_data

contacts = contacts()
print(contacts)

Hope this helps !
If it does, please consider marking this answer as a solution :slightly_smiling_face:

Best,

Ludwig