API / Add contacts to a static list

Hello,

Context:
Every week I do two to three contact imports that I add to a statistical list afterwards to trigger a workflow (send emails).
I want to automate these imports using Python/API-HubSpot.
I coded a code that doesn’t work, I don’t really understand where the error comes from.

What I want to do: import contacts on HubSpot with the API and then add them in my static list.

My code:

```

AddList = “https://api.hubapi.com/contacts/v1/lists/LIST_ID/add?hapikey=API-Key”

emailList = “”

with open(“contacts - in.csv”) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=‘,’)
line_count = 0
for row in csv_reader:
# This will skip the header row;
if line_count == 0:
line_count += 1
pass
else:
# My emails happen to be in column c, you may need to change this.
# If the csv file is open in excel column A = 0, B = 1, C = 2, D = 3…
emailList += “\”“+row[2] + “\”,\n”
line_count += 1

mydata = “”“{
“vids”: [],
“emails”: [
“””+emailList[:-2]+“”" #This will remove the extra spaces and characters at the end
]
}“”"

headers = {‘content-type’: ‘application/json’}

response = requests.request(“POST”, AddList, headers = headers, data = mydata)
print(response.text.encode(‘utf8’))
print(response.status_code)

```

ERROR:

Thanks for your help :slightly_smiling_face:

@AbdelMOULIDA ,

Any possibility of printing out what the json body looks like that you are sending?

Hello @dennisedson , thanks for your feedback.

If the contact already exist on HubSpot (It works):

If the contact doesn’t exist on HubSpot, I have this error and the contact is not created:

AbdelMOULIDA_2-1626188748297.png

@AbdelMOULIDA , the contact needs to exist before you can add it to the list.

Hi @AbdelMOULIDA ,
Your input data contains “#” inside it which is a special character and need to be escaped.Do the string escaping of your content before passing the info through json.

Hope this helps!

If we were able to answer your query, kindly help the community by marking it as a solution.
Thanks and Regards.

Hi @webdew ,

Thank you, It works :).

Best regards.