Reputation: 149
I am new to Mailchimp api. I have this csv file which has list of subscribers, that needs to be bulk exported to mailchimp. I initially thought of iterating each as json object in for loop and make apic calls, but that does not seem to work. Then on further reading discovered batch operations. I am trying to format per batch request but i get an error : {"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Missing","status":401,"detail":"Your request did not include an API key.","instance":"XXX"}
import requests
import csv
import json
import glob
import os
from mailchimp3 import MailChimp
username = 'abc'
apikey = 'xxyyzzz'
url = "https://us12.api.mailchimp.com/3.0/lists/XXXX/members"
headers = {'Content-Type': 'application/json'}
primary_fields = [ 'email_address','status']
result = []
for filename in glob.glob('D:\\abc.csv'):
csvfile = os.path.splitext(filename)[0]
jsonfile = csvfile + '.json'
with open('D:\\abc.csv', encoding="ISO-8859-1") as csv_file:
reader = csv.DictReader(csv_file, skipinitialspace=True)
for row in reader:
d = {k: v for k, v in row.items() if k in primary_fields}
d['merge_fields'] = {k: v for k, v in row.items() if k not in primary_fields}
result.append(d)
with open(jsonfile, 'w')as fp:
json.dump(result, fp, indent=2)
client = MailChimp(mc_api=apikey, mc_user= username)
with open("D:\\abc.json", "r") as read_file:
data= json.load(read_file)
#Create list for dictionaries
operations = []
#loop through queryset
for item in data:
#Create dictionary for a operation
operation_item = {"method":"POST", "path":"/lists/XXXX/members/", "body":json.dumps(data)}
#Append to list
operations.append(operation_item)
client = MailChimp(mc_api=apikey, mc_user= username)
batch = client.batches.create(data={"operations": operations})
Upvotes: 2
Views: 665
Reputation: 11
The Authorization field is missing in the header.
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic YOURAPIKEY'}
Upvotes: 1