Mailchimp API v3 Wrapper
The `mailchimp-api-v3` library, currently at version 1.15.0, provides a comprehensive Node.js wrapper for the Mailchimp API v3. It distinguishes itself by offering transparent handling of Mailchimp's batch operations, allowing developers to execute multiple API calls as a single logical unit with seamless polling and result unpacking. The library supports both traditional callback-based asynchronous programming and modern Promise-based patterns, enhancing flexibility for various project styles. It aims to simplify integration by closely mirroring the Mailchimp API v3 documentation structure, enabling direct mapping of API paths and parameters. While its release cadence isn't explicitly stated, version 1.15.0 indicates active development at some point. Its core value lies in abstracting away the complexities of batch request management and providing a consistent interface for the RESTful Mailchimp API. It is primarily used for server-side integration with Mailchimp services.
Common errors
-
Error: "Unauthorized" (or HTTP Status 401)
cause The Mailchimp API key provided during client instantiation is invalid or has insufficient permissions.fixVerify your Mailchimp API key is correct and has the necessary permissions for the requested operation. Ensure there are no leading/trailing spaces or typos. -
Error: "Resource Not Found" (or HTTP Status 404)
cause The API path or an ID within the path (e.g., list ID, member ID) is incorrect or does not exist.fixDouble-check the API path string and any IDs (e.g., list_id, member_id) against your Mailchimp account and the Mailchimp API documentation. Ensure IDs are URL-encoded if they contain special characters. -
TypeError: mailchimp.get is not a function
cause The `Mailchimp` class constructor was called without the `new` keyword, or the `mailchimp` object was not correctly instantiated.fixEnsure you are instantiating the Mailchimp client correctly: `const mailchimp = new Mailchimp(apiKey);`. -
Error: connect ETIMEDOUT (or other network-related errors)
cause The application could not establish a network connection to the Mailchimp API server, often due to firewall restrictions, proxy issues, or temporary network outages.fixCheck your network connectivity, firewall settings, and any configured proxy settings. Ensure that your server or development environment can reach `api.mailchimp.com` over HTTPS (port 443).
Warnings
- gotcha Mailchimp API keys provide full access to your Mailchimp account. Never hardcode API keys directly in client-side code or commit them to version control. Always use environment variables or a secure configuration management system.
- gotcha The `batch` operation defaults to `wait: true` and `unpack: true`. While convenient, for very large batch operations or slow Mailchimp processing times, this can lead to long-running requests that might exceed typical serverless function timeouts or client-side request limits. The client will poll Mailchimp until the batch is complete.
- gotcha The library primarily supports CommonJS `require()` syntax. While it might work with some bundlers or transpilers to enable `import` statements, official ESM support is not explicitly documented, which can lead to issues in modern Node.js environments configured for native ESM.
- gotcha The `path` parameter for `mailchimp.request` and shorthand methods (`get`, `post`, etc.) can be specified with or without path parameters. For example, `/lists/{list_id}` with `path_params: { list_id: 'abc' }` or directly as `/lists/abc`. Inconsistent usage can lead to API errors.
Install
-
npm install mailchimp-api-v3 -
yarn add mailchimp-api-v3 -
pnpm add mailchimp-api-v3
Imports
- Mailchimp
import { Mailchimp } from 'mailchimp-api-v3';const Mailchimp = require('mailchimp-api-v3'); - Mailchimp class instantiation
const mailchimp = Mailchimp(apiKey);
const mailchimp = new Mailchimp(apiKey);
Quickstart
const Mailchimp = require('mailchimp-api-v3');
const MAILCHIMP_API_KEY = process.env.MAILCHIMP_API_KEY ?? 'YOUR_MAILCHIMP_API_KEY'; // Replace with a real key or env var
if (MAILCHIMP_API_KEY === 'YOUR_MAILCHIMP_API_KEY') {
console.warn('WARNING: Using placeholder Mailchimp API key. Set process.env.MAILCHIMP_API_KEY for real use.');
}
const mailchimp = new Mailchimp(MAILCHIMP_API_KEY);
async function getAudienceLists() {
try {
// Fetch all audience lists associated with the API key
const result = await mailchimp.get('/lists');
console.log('Successfully retrieved audience lists:');
if (result && result.lists && result.lists.length > 0) {
result.lists.forEach((list) => {
console.log(`- ID: ${list.id}, Name: ${list.name}, Members: ${list.stats.member_count}`);
});
} else {
console.log('No audience lists found.');
}
} catch (err) {
console.error('Error fetching lists:', err.message);
if (err.statusCode) {
console.error('Mailchimp API Error Status:', err.statusCode);
console.error('Mailchimp API Error Detail:', err.detail);
} else {
console.error('Network or other error:', err);
}
}
}
getAudienceLists();