MailChimp: Add email to subscription list with Python

I’m working on a simple app for a friend I met at a Hackathon a few weeks back to kind of build a AirBnB for Community Dinners and had to integrate mail list subscriptions into the app. So he provided me with his mailchimp credentials and I started to research into their API. Since I have hundreds of thousands of lines of code written in Python from past projects I decided to throw together a quick RESTful API to handle Subscription requests to Mailchimp using Flask and the “mailchimp” module.

At first look the mailchimp python module has horrible documentation and it would have likely been easier for me to just write my own wrapper around their API but decided to give it a whirl. Turns out it is pretty easy to accomplish this task with the following code:

The code

#!/usr/bin/env python
from flask import Flask, request
from flask.ext.cors import CORS
from flask_restful import Resource, Api
from mailchimp import Mailchimp
from validate_email import validate_email

application = Flask(__name__)
api = Api(application)

class SubscribeList(Resource):
    Handle Mail list subscription

    def post(self):
        data = request.get_json(force=True)
        email = data.get('email')
        if email and validate_email(email):
            api_key = '' # API Key
            payload = {
                "id": "", # Mail List ID
                "email": {
                    "email": email
            mc = Mailchimp(api_key, True)
  'lists/subscribe', payload)
            return {"success": True}
            return {"error": True}

# List of Routes
api.add_resource(SubscribeList, '/subscribe')

# Run Flask App
if __name__ == '__main__':'')

Now there are likely methods in the Mailchimp package to handle subscribing to a list; but there was no documentation and the python package is auto generated so its not the most readable; however I was able to find the low level call method to use to send my own parameters to the API – which is how I recommend you do it unless you want to read said non existent documentation or roll your own API wrapper.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.