Question

I'm trying to interact with the mailchimp api and I'm having issues with the subscribe method. I've tracked down the problem to where I encode the data. It seems to be that urllib.urlencode isn't encoding my struct correctly. The struct in question is: {'email':{'email':'example@email.com'}} My question is, what is the proper way to send a struct through a request with urllib2?

Was it helpful?

Solution

According to their documentation, MailChimp expects data to be JSON (with the correct content-type header), not URL-encoded form data.

Using urllib2, here's an example on how to POST JSON data with the correct header, taken from this answer :

import urllib2

data = "{'email':{'email':'example@email.com'}}"
req = urllib2.Request("http://some/API/endpoint", data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

However, I suggest you use Python-Requests which is easier to use than urllib2, here's the same code using Requests :

from requests import post

data = "{'email':{'email':'example@email.com'}}"
response = post("http://some/API/endpoint", data=data, headers={'Content-type': 'application/json', 'Accept': 'text/plain'}).text
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top