# Mass Deleting Contact/Company Associations via Python Custom Code Workflow

**URL:** <https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979>\
**Category:** APIs & Integrations\
**Tags:** python, companies, workflows, contacts\
**Created:** [August 21, 2023, 9:23pm UTC](https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979 "2023-08-21T21:23:36Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jjones41](https://avatars.discourse-cdn.com/v4/letter/j/c67d28/32.png) [@jjones41](https://community.hubspot.com/u/jjones41)\
**Post date:** [August 21, 2023, 9:23pm UTC](https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979/1 "2023-08-21T21:23:36Z")

</div>

Hello all,  
I am working on a custom code workflow that I can share with the community to bulk delete contact/company associations. I needed this, found it was a frustration for many, and decided to build it and share. However, I’m struggling a little.  
[This code](https://github.com/jjonesfbs/HubSpot_Resources/blob/main/Bulk%20Delete%20Company%20Contact%20Associations) works perfectly for companies with ~50 or so contacts. However, it times out for companies with more contacts.  
So I tried to modify to batch delete, but I just can’t get it right. I find the contacts, batch out the IDs, but can’t seem to figure out how to delete them correctly. Any thoughts or help would be much appreciated. Here’s the code as it stands:

import os  
import requests

# Function to delete associations between a company and contacts in batches  
def delete\_associations\_in\_batches(api\_key, company\_id, contact\_ids, batch\_size=10):  
headers = {  
“Authorization”: f"Bearer {api\_key}",  
“Content-Type”: “application/json”  
}  
from\_object\_type = “company”  
to\_object\_type = “contact”

for i in range(0, len(contact\_ids), batch\_size):  
batch\_contact\_ids = contact\_ids[i:i+batch\_size]

batch\_payload = []  
for contact\_id in batch\_contact\_ids:  
batch\_payload.append({  
“fromObjectId”: company\_id,  
“toObjectId”: contact\_id  
})

batch\_url = f"[https://api.hubapi.com/crm/v4/associations/{from\_object\_type}/{to\_object\_type}/batch/archive](https://api.hubapi.com/crm/v4/associations/%7Bfrom_object_type%7D/%7Bto_object_type%7D/batch/archive)"  
batch\_response = requests.post(batch\_url, headers=headers, json=batch\_payload)

if batch\_response.status\_code == 204:  
print(f"Associations deleted in batch for company {company\_id} and contacts: {batch\_contact\_ids}“)  
else:  
print(f"Error deleting associations in batch: {batch\_response.status\_code}”)

def main(event):  
# Retrieve the API key and company ID from environment variables (secrets)  
api\_key = os.getenv(“Salty\_Breakfast\_Key”)  
company\_id = event.get(‘inputFields’).get(‘companyID’)

# API endpoints  
company\_url = f"[https://api.hubapi.com/crm/v3/objects/companies/{company\_id](https://api.hubapi.com/crm/v3/objects/companies/%7Bcompany_id)}"  
association\_url = f"[https://api.hubapi.com/crm/v3/objects/companies/{company\_id}/associations/contacts](https://api.hubapi.com/crm/v3/objects/companies/%7Bcompany_id%7D/associations/contacts)"

headers = {  
“Authorization”: f"Bearer {api\_key}“,  
“Content-Type”: “application/json”  
}  
# Retrieve company information  
company\_response = requests.get(company\_url, headers=headers)  
if company\_response.status\_code == 200:  
company\_data = company\_response.json()  
company\_name = company\_data.get(“properties”, {}).get(“name”, “Company Name Not Found”)  
print(f"Company Name: {company\_name}”)  
else:  
error\_message = f"Error fetching company information: {company\_response.status\_code}"  
print(error\_message)  
return error\_message

# Step 1: Retrieve record IDs of associated contacts  
contacts\_response = requests.get(association\_url, headers=headers)  
if contacts\_response.status\_code == 200:  
contacts\_data = contacts\_response.json()  
contact\_ids = [assoc[“id”] for assoc in contacts\_data.get(“results”, [])]

if contact\_ids:  
delete\_associations\_in\_batches(api\_key, company\_id, contact\_ids, batch\_size=10)  
else:  
print(“No associated contacts to delete.”)  
else:  
print(f"Error fetching associated contacts: {contacts\_response.status\_code}")

# Call the main function  
if \_\_name\_\_ == “\_\_main\_\_”:  
main(None)

---

<div class="post-metadata">

**Author:** ![Sawdog](https://avatars.discourse-cdn.com/v4/letter/s/ecd19e/32.png) [@Sawdog](https://community.hubspot.com/u/Sawdog)\
**Post date:** [August 21, 2023, 11:25pm UTC](https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979/2 "2023-08-21T23:25:28Z")

</div>

Are you constructing the payload properly; this is what I see in the docs:

```lia-code-sample
 "inputs": [
 {
 "from": {
 "id": "string"
 },
 "to": [
 {
 "id": "string"
 }
 ]
 }
 ]

```

Not “fromObjectId” or “toObjectId”…  
Are you getting any helpful response? I would assume you could run into a similar timeout problem if the list was large enough if it’s due to time spent looping? Maybe you could setup a session that’s reusable … and/or has some keep alive that might help with dealing with the timeout issue.

---

<div class="post-metadata">

**Author:** ![jjones41](https://avatars.discourse-cdn.com/v4/letter/j/c67d28/32.png) [@jjones41](https://community.hubspot.com/u/jjones41)\
**Post date:** [August 22, 2023, 2:37pm UTC](https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979/3 "2023-08-22T14:37:44Z")

</div>

Thanks, @Sawdog. Simple enough. This was my first API project ever, so I’m learning lots. Got the payload restructured, and it works great. It can still timeout if it’s trying to clear \> ~500 or so contacts. Eventually, I’ll work to improve that. Given Hubspot’s retry approach, all in all, this will clear ~2,500 contacts in \< 10 minutes. That should work fine for pretty much all the posts I’ve seen on the topic.

---

<div class="post-metadata">

**Author:** ![Sawdog](https://avatars.discourse-cdn.com/v4/letter/s/ecd19e/32.png) [@Sawdog](https://community.hubspot.com/u/Sawdog)\
**Post date:** [August 22, 2023, 3:52pm UTC](https://community.hubspot.com/t/mass-deleting-contact-company-associations-via-python-custom-code-workflow/87979/4 "2023-08-22T15:52:08Z")

</div>

Hey, that’s great - and congrats on your first API! Good job. IIRC your batch size was 10. Increase your batch to 100. Then there’s a few approaches you could take to avoid the timeout; depends on what’s going on. If you don’t care about performance, and just care that it runs… You can recreate a new connection for every batch. So it will not try to keep the connection open (which is what I suspect is timing out). Are you getting a timeout explicitly - or is the connection just being closed? The later can be harder to handle. You can learns some more fun stuff using async - using AIOHTTP. Check into keep alive with requests, requests sessions, and the hubspot API. The API endpoints might not support keep alive… So facing the timeout is just always… a metter of time. 🙂

Glad it’s working!
