A Ruby gem for interacting with the Mailchimp Marketing API. This gem provides a clean, intuitive interface for working with Mailchimp's REST API, featuring automatic retries, pagination support, and comprehensive error handling.
- Supports Ruby versions: 2.6 through 3.3, head, jruby-9.4, truffleruby-24
- Zero dependencies
- Configurable auto-retries
- Built-in pagination support
- Comprehensive error handling
- Clean, intuitive API interface
Add this line to your application's Gemfile:
gem 'mailchimp-rest-api'
And then execute:
bundle install
# Configure the client
MailchimpAPI.client = MailchimpAPI::Client.new(
api_key: ENV['MAILCHIMP_API_KEY']
)
# Example: Add a member to an audience
response = MailchimpAPI.audience_members.create(
'audience_id',
body: {
email_address: 'user@example.com',
status: 'subscribed',
merge_fields: {
FNAME: 'John',
LNAME: 'Doe'
}
}
)
puts response.body[:status]
The client accepts several configuration options:
client = MailchimpAPI::Client.new(
api_key: ENV['MAILCHIMP_API_KEY'],
retries: {
enabled: true,
count: 4,
sleep: [0, 0.25, 0.75, 1.5] # Retry delays in seconds
},
http_opts: {
read_timeout: 30,
write_timeout: 30,
open_timeout: 30
}
)
By default, the client will retry failed requests with the following configuration:
- Enabled: true
- Retry count: 4
- Delay between retries: 0, 0.25, 0.75, 1.5 seconds
Retries are triggered for:
- Network errors
- HTTP status codes: 409, 429, and 5xx responses
You can configure various HTTP options that are passed to Net::HTTP.start
. Common options include:
read_timeout
write_timeout
open_timeout
You can make HTTP requests directly:
# GET request
response = MailchimpAPI.get('/lists/<list_id>/members')
# POST request
response = MailchimpAPI.post(
'/lists/<list_id>/members',
body: { email_address: 'user@example.com' }
)
The response object provides several useful methods:
response = MailchimpAPI.get('/some/path')
# Check response status
response.success? # true for 2xx status codes
response.failed? # true for non-2xx status codes
# Access response data
response.body # Parsed JSON body (symbolized keys)
response[:field] # Access specific field (returns nil if missing)
response.fetch(:field) # Access field (raises KeyError if missing)
# Access HTTP details
response.http_status
response.http_body
response.http_headers
The gem provides specific error classes for different types of errors:
begin
MailchimpAPI.audience_members.create(audience_id, body: body)
rescue MailchimpAPI::Errors::UnprocessableEntity => e
puts "Validation failed: #{e.error_detail}"
puts "Field errors: #{e.error_fields}"
rescue MailchimpAPI::Errors::NetworkError => e
puts "Network error: #{e.error_detail}"
end
Available error classes:
NetworkError
- Network-related issuesBadRequest
(400) - Invalid request parametersUnauthorized
(401) - Invalid API keyForbidden
(403) - Insufficient permissionsNotFound
(404) - Resource not foundUnprocessableEntity
(422) - Request validation failedTooManyRequests
(429) - Rate limit exceededServerError
(5xx) - Mailchimp server error
Most resources support this APIs:
list
- List itemscreate
- Create new itemshow
- Get item detailsupdate
- Update itemdelete
- Delete itemeach
- Iterate through items
list
- List audiences (lists)create(list_id, body: {})
- Add audienceshow(list_id)
- Show audienceupdate(list_id, body: {})
- Update audiencedelete(list_id)
- Delete audienceeach(list_id)
- Iterate audiencesbatch_update_members(list_id, body: {})
- Batch update audience members
list(list_id)
- List memberscreate(list_id, body: { email_address: 'x', status: 'x' })
- Add membershow(list_id, email)
- Get memberupdate(list_id, email, body: { status: 'x' })
- Update memberarchive(list_id, email)
- Archive memberadd_or_update(list_id, email, body: { status: 'x' })
- Upsert memberdelete_permanent(list_id, email)
- Permanently deleteeach(list_id)
- Iterate members
list(list_id, email)
- List tagscreate(list_id, email, body: { tags: [{name: 'x'}] })
- Add tagseach(list_id, email)
- Iterate tags
list(list_id)
- List merge fieldscreate(list_id, body: { name: 'x' })
- Create merge fieldshow(list_id, field_id)
- Get merge fieldupdate(list_id, field_id, body: { name: 'x' })
- Update merge fielddelete(list_id, field_id)
- Delete merge fieldeach(list_id)
- Iterate merge fields
list(list_id)
- List segmentscreate(list_id, body: { name: 'x' })
- Create segmentshow(list_id, segment_id)
- Get segmentupdate(list_id, segment_id, body: { name: 'x' })
- Update segmentdelete(list_id, segment_id)
- Delete segmentbatch_add_or_remove_members(list_id, segment_id, body: { members_to_add: [] })
- Bulk modifyeach(list_id)
- Iterate segments
list(list_id, segment_id)
- List segment memberscreate(list_id, segment_id, body: { email_address: 'x' })
- Add segment memberdelete(list_id, segment_id, email)
- Remove segment membereach(list_id, segment_id)
- Iterate segment members
list(list_id)
- List categoriescreate(list_id, body: { title: 'x', type: 'x' })
- Create categoryshow(list_id, category_id)
- Get categoryupdate(list_id, category_id, body: { title: 'x' })
- Update categorydelete(list_id, category_id)
- Delete categoryeach(list_id)
- Iterate categories
list(list_id, category_id)
- List interestscreate(list_id, category_id, body: { name: 'x' })
- Create interestshow(list_id, category_id, interest_id)
- Get interestupdate(list_id, category_id, interest_id, body: { name: 'x' })
- Update interestdelete(list_id, category_id, interest_id)
- Delete interesteach(list_id, category_id)
- Iterate interests
list(list_id)
- List webhookscreate(list_id, body: { url: 'x', events: {} })
- Create webhookshow(list_id, webhook_id)
- Get webhookupdate(list_id, webhook_id, body: { events: {} })
- Update webhookdelete(list_id, webhook_id)
- Delete webhookeach(list_id)
- Iterate webh
list
- List campaignscreate(body: {})
- Create campaignshow(campaign_id)
- Get campaignupdate(campaign_id, body: {})
- Update campaigndelete(campaign_id)
- Delete campaigneach
- Iterate campaigns
show(campaign_id)
- Shows campaign contentupdate(campaign_id, body: {})
- Updates HTML and text campaign content
list
- List campaign folderscreate(body: {})
- Create campaign foldershow(folder_id)
- Get campaign folderupdate(folder_id, body: {})
- Update campaign folderdelete(folder_id)
- Delete campaign foldereach
- Iterate campaign folders
Most resources support pagination through the each
method:
# Iterate through all members
MailchimpAPI.audience_members.each(audience_id) do |member|
puts member['email_address']
end
# Configure page size
MailchimpAPI.audience_members.each(audience_id, query: { count: 100 }) do |member|
puts member['email_address']
end
After checking out the repo, run:
bundle install
To run tests:
bundle exec rspec
To run linters:
bundle exec rubocop
bundle exec mdl README.md CHANGELOG.md RELEASE.md
Bug reports and pull requests are welcome on GitHub at https://github.com/andreyruby/mailchimp-rest-api.
The gem is available as open source under the terms of the MIT License.