I wrote a python code for my hubspot software and it does not work as expected. I have an original deal (original_deal_id) and a therefrom created deal (hs_object_id). Now I want to associate the original deal with "maincourse" and the new deal with "precourse".
I've tried this code but the associations are not displayed
# create new "precourse" (id 32) and "maincourse" (id 33) user-defined associations if not already exists
import requests
import json
import time
def main(event):
token = 'pat-na1-d8c379bb-9789-4083-a0a9-d4fb8383c806'
base_url = 'https://api.hubapi.com/crm/v4'
sleeptime = 2 # wait time in seconds if API request limit reached
hs_object_id = event.get('inputFields').get('hs_object_id') # ID of the new deal
original_deal_id = event.get('inputFields').get('original_deal_id') # ID of the main deal
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
'accept': 'application/json'
}
# Modify payload to include "precourse" association
precourse_payload = [{'associationCategory': 'USER_DEFINED', 'associationTypeId': 32}] # precourse
# Replace X with the actual association type ID for "maincourse"
maincourse_payload = [{'associationCategory': 'USER_DEFINED', 'associationTypeId': 33}] # maincourse
try:
# Associate "precourse" label with the new deal
status_code = 429
while status_code == 429: # code 429 == API request limit reached
req = requests.put(
url=f'{base_url}/objects/deal/{hs_object_id}/associations/deal/{original_deal_id}',
data=json.dumps(precourse_payload),
headers=headers
)
status_code = req.status_code
if status_code == 429:
time.sleep(sleeptime) # short wait time and then request again
if status_code == 201:
print(f'Successfully associated with "precourse" label.')
else:
print(f'Failed to associate with "precourse" label. Status code: {status_code}. Response: {req.text}')
# Associate "maincourse" label with the original deal
status_code = 429
while status_code == 429: # code 429 == API request limit reached
req = requests.put(
url=f'{base_url}/objects/deal/{original_deal_id}/associations/deal/{hs_object_id}',
data=json.dumps(maincourse_payload),
headers=headers
)
status_code = req.status_code
if status_code == 429:
time.sleep(sleeptime) # short wait time and then request again
if status_code == 201:
print(f'Successfully associated with "maincourse" label.')
else:
print(f'Failed to associate with "maincourse" label. Status code: {status_code}. Response: {req.text}')
except Exception as e:
print(f'Exception when processing deals: {e}')
return {}