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?
Asked
Active
Viewed 149 times
1

neatnick
- 1,489
- 1
- 18
- 29
-
I don't know what mailchimp is expecting, but there is no "proper" way to send a structure in an HTML request. – Gabe Jan 15 '14 at 01:24
1 Answers
3
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

Community
- 1
- 1
-
Hey Andre, I like your requests example. How do you check the response for good vs. error operation? – arcee123 Jan 04 '15 at 06:50
-
@arcee123 if the request itself failed due a network error an exception will be raised; if the request succeeded but the server returned an error you should check the response contents and see what the server said; refer to the API's documentation for possible error responses. – Jan 04 '15 at 09:47