Fraxr
Fraxr

Reputation: 125

Add a member using python requests and Mailchimp API v3

I am trying to learn more about using http requests and the Mailchimp API, but I cannot seem to figure out how to add a member to list using a post request. I have tried multiple configurations, and I guess I made some headway since my response went from a 405, to a 401, now I'm getting a 400. I assume this means that I am being authenticated, but I am formatting the request incorrectly.

I have gotten it to work the python mailchimp library, but I want to actually learn how to use the HTTP requests. I could find very few examples of using python requests with Mailchimp.

(obviously I put in my actual list_id, my_username, and my_apikey)

import requests, json


members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}


data1 = {
    'email_address':'[email protected]',
    'status':'subscribed',
    'merge_fields':{
        'FNAME':'John',
        'LNAME':'Doe'
        }
    }

payload = json.dumps(data1)

response = requests.post(members_url, auth=auth, headers=headers, json=payload)

This is my response:

>>> response
<Response [400]>

I'm stumped....what am I doing wrong?

This worked:

import requests, json


members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}


data1 = {
    'email_address':'<a real email address>',  #it could tell '[email protected] was fake'
    'status':'subscribed',
    'merge_fields':{
        'FNAME':'John',
        'LNAME':'Doe'
        }
    }

response = requests.post(members_url, auth=auth, headers=headers, json=data1)

Upvotes: 2

Views: 1880

Answers (1)

Fraxr
Fraxr

Reputation: 125

This worked:

import requests, json


members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}


data1 = {
    'email_address':'<a real email address>',  #it could tell '[email protected] was fake'
    'status':'subscribed',
    'merge_fields':{
        'FNAME':'John',
        'LNAME':'Doe'
        }
    }

response = requests.post(members_url, auth=auth, headers=headers, json=data1)

My problems were #1 I was double encoding the json data and #2 mailchimp recognizes obviously BS email addresses like [email protected]

Thanks @Alasdair

Upvotes: 5

Related Questions