Mailchimp REST API (Marketing)
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.
Features
- 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
Installation
Add this line to your application's Gemfile:
gem 'mailchimp-rest-api'
And then execute:
bundle install
Quick Start
# 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]
Configuration
Client Configuration
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
}
)
Retry Configuration
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
HTTP Options
You can configure various HTTP options that are passed to Net::HTTP.start
. Common options include:
read_timeout
write_timeout
open_timeout
API Usage
Making Requests
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' }
)
Working with Responses
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
Error Handling
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 issues -
BadRequest
(400) - Invalid request parameters -
Unauthorized
(401) - Invalid API key -
Forbidden
(403) - Insufficient permissions -
NotFound
(404) - Resource not found -
UnprocessableEntity
(422) - Request validation failed -
TooManyRequests
(429) - Rate limit exceeded -
ServerError
(5xx) - Mailchimp server error
Resources
Most resources support this APIs:
-
list
- List items -
create
- Create new item -
show
- Get item details -
update
- Update item -
delete
- Delete item -
each
- Iterate through items
MailchimpAPI.audiences
-
list
- List audiences (lists) -
create(list_id, body: {})
- Add audience -
show(list_id)
- Show audience -
update(list_id, body: {})
- Update audience -
delete(list_id)
- Delete audience -
each(list_id)
- Iterate audiences -
batch_update_members(list_id, body: {})
- Batch update audience members
MailchimpAPI.audience_members
-
list(list_id)
- List members -
create(list_id, body: { email_address: 'x', status: 'x' })
- Add member -
show(list_id, email)
- Get member -
update(list_id, email, body: { status: 'x' })
- Update member -
archive(list_id, email)
- Archive member -
add_or_update(list_id, email, body: { status: 'x' })
- Upsert member -
delete_permanent(list_id, email)
- Permanently delete -
each(list_id)
- Iterate members
MailchimpAPI.audience_member_tags
-
list(list_id, email)
- List tags -
create(list_id, email, body: { tags: [{name: 'x'}] })
- Add tags -
each(list_id, email)
- Iterate tags
MailchimpAPI.audience_merge_fields
-
list(list_id)
- List merge fields -
create(list_id, body: { name: 'x' })
- Create merge field -
show(list_id, field_id)
- Get merge field -
update(list_id, field_id, body: { name: 'x' })
- Update merge field -
delete(list_id, field_id)
- Delete merge field -
each(list_id)
- Iterate merge fields
MailchimpAPI.audience_segments
-
list(list_id)
- List segments -
create(list_id, body: { name: 'x' })
- Create segment -
show(list_id, segment_id)
- Get segment -
update(list_id, segment_id, body: { name: 'x' })
- Update segment -
delete(list_id, segment_id)
- Delete segment -
batch_add_or_remove_members(list_id, segment_id, body: { members_to_add: [] })
- Bulk modify -
each(list_id)
- Iterate segments
MailchimpAPI.audience_segment_members
-
list(list_id, segment_id)
- List segment members -
create(list_id, segment_id, body: { email_address: 'x' })
- Add segment member -
delete(list_id, segment_id, email)
- Remove segment member -
each(list_id, segment_id)
- Iterate segment members
MailchimpAPI.audience_interest_categories
-
list(list_id)
- List categories -
create(list_id, body: { title: 'x', type: 'x' })
- Create category -
show(list_id, category_id)
- Get category -
update(list_id, category_id, body: { title: 'x' })
- Update category -
delete(list_id, category_id)
- Delete category -
each(list_id)
- Iterate categories
MailchimpAPI.audience_interests
-
list(list_id, category_id)
- List interests -
create(list_id, category_id, body: { name: 'x' })
- Create interest -
show(list_id, category_id, interest_id)
- Get interest -
update(list_id, category_id, interest_id, body: { name: 'x' })
- Update interest -
delete(list_id, category_id, interest_id)
- Delete interest -
each(list_id, category_id)
- Iterate interests
MailchimpAPI.audience_webhooks
-
list(list_id)
- List webhooks -
create(list_id, body: { url: 'x', events: {} })
- Create webhook -
show(list_id, webhook_id)
- Get webhook -
update(list_id, webhook_id, body: { events: {} })
- Update webhook -
delete(list_id, webhook_id)
- Delete webhook -
each(list_id)
- Iterate webh
MailchimpAPI.campaigns
-
list
- List campaigns -
create(body: {})
- Create campaign -
show(campaign_id)
- Get campaign -
update(campaign_id, body: {})
- Update campaign -
delete(campaign_id)
- Delete campaign -
each
- Iterate campaigns
MailchimpAPI.campaign_content
-
show(campaign_id)
- Shows campaign content -
update(campaign_id, body: {})
- Updates HTML and text campaign content
MailchimpAPI.campaign_folders
-
list
- List campaign folders -
create(body: {})
- Create campaign folder -
show(folder_id)
- Get campaign folder -
update(folder_id, body: {})
- Update campaign folder -
delete(folder_id)
- Delete campaign folder -
each
- Iterate campaign folders
Pagination
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
Development
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
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/andreyruby/mailchimp-rest-api.
License
The gem is available as open source under the terms of the MIT License.