Back

Step by Step Guide to Building a Campaign Monitor API Integration in Java

Aug 13, 20249 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your email marketing game with Campaign Monitor's API? You're in the right place. This guide will walk you through integrating Campaign Monitor's powerful features into your Java application. Let's dive in and make some magic happen!

Prerequisites

Before we start coding, make sure you've got these basics covered:

  • A Java development environment (I know you've got this!)
  • A Campaign Monitor account with an API key (if you don't have one, go grab it real quick)
  • Your favorite HTTP client library (we'll be using OkHttp in this guide, but feel free to use what you're comfortable with)

Setting up the project

Alright, let's get our hands dirty! Create a new Java project in your IDE of choice. If you're using Maven, add this to your pom.xml:

<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.10.0</version> </dependency>

For Gradle users, pop this into your build.gradle:

implementation 'com.squareup.okhttp3:okhttp:4.10.0'

Authentication

Now, let's set up our base client class. This will handle authentication and serve as the foundation for our API calls:

import okhttp3.*; import java.io.IOException; public class CampaignMonitorClient { private final OkHttpClient client; private final String apiKey; private final String baseUrl = "https://api.createsend.com/api/v3.2/"; public CampaignMonitorClient(String apiKey) { this.apiKey = apiKey; this.client = new OkHttpClient(); } public String makeRequest(String endpoint, String method, String body) throws IOException { Request.Builder requestBuilder = new Request.Builder() .url(baseUrl + endpoint) .header("Authorization", Credentials.basic(apiKey, "x")) .header("Content-Type", "application/json"); if (body != null) { requestBuilder.method(method, RequestBody.create(body, MediaType.get("application/json"))); } else { requestBuilder.method(method, null); } try (Response response = client.newCall(requestBuilder.build()).execute()) { return response.body().string(); } } }

Core API functionalities

Subscribers

Let's start with the bread and butter of email marketing: managing subscribers.

public class SubscriberManager { private final CampaignMonitorClient client; public SubscriberManager(CampaignMonitorClient client) { this.client = client; } public void addSubscriber(String listId, String email, String name) throws IOException { String body = String.format("{\"EmailAddress\": \"%s\", \"Name\": \"%s\"}", email, name); client.makeRequest("subscribers/" + listId + ".json", "POST", body); } public void updateSubscriber(String listId, String email, String newName) throws IOException { String body = String.format("{\"EmailAddress\": \"%s\", \"Name\": \"%s\"}", email, newName); client.makeRequest("subscribers/" + listId + ".json?email=" + email, "PUT", body); } public void unsubscribe(String listId, String email) throws IOException { String body = String.format("{\"EmailAddress\": \"%s\"}", email); client.makeRequest("subscribers/" + listId + "/unsubscribe.json", "POST", body); } }

Lists

Next up, let's handle list management:

public class ListManager { private final CampaignMonitorClient client; public ListManager(CampaignMonitorClient client) { this.client = client; } public String createList(String clientId, String title) throws IOException { String body = String.format("{\"Title\": \"%s\"}", title); return client.makeRequest("lists/" + clientId + ".json", "POST", body); } public String getListDetails(String listId) throws IOException { return client.makeRequest("lists/" + listId + ".json", "GET", null); } }

Campaigns

Finally, let's create and send campaigns:

public class CampaignManager { private final CampaignMonitorClient client; public CampaignManager(CampaignMonitorClient client) { this.client = client; } public String createCampaign(String clientId, String name, String subject, String listId, String htmlContent) throws IOException { String body = String.format( "{\"Name\": \"%s\", \"Subject\": \"%s\", \"ListIDs\": [\"%s\"], \"HTMLContent\": \"%s\"}", name, subject, listId, htmlContent ); return client.makeRequest("campaigns/" + clientId + ".json", "POST", body); } public void sendCampaign(String campaignId) throws IOException { client.makeRequest("campaigns/" + campaignId + "/send.json", "POST", "{}"); } }

Error handling and best practices

When working with APIs, always expect the unexpected! Here are some tips:

  1. Implement retry logic for rate limiting:
public String makeRequestWithRetry(String endpoint, String method, String body) throws IOException { int maxRetries = 3; int retryDelay = 1000; // 1 second for (int i = 0; i < maxRetries; i++) { try { return makeRequest(endpoint, method, body); } catch (IOException e) { if (e.getMessage().contains("429 Too Many Requests") && i < maxRetries - 1) { Thread.sleep(retryDelay * (i + 1)); } else { throw e; } } } throw new IOException("Max retries exceeded"); }
  1. Always check for and handle error responses from the API.
  2. Use logging to track API calls and responses for easier debugging.

Testing the integration

Don't forget to test your integration thoroughly! Here's a quick example using JUnit:

import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CampaignMonitorIntegrationTest { private final CampaignMonitorClient client = new CampaignMonitorClient("your-api-key"); private final SubscriberManager subscriberManager = new SubscriberManager(client); @Test public void testAddSubscriber() { assertDoesNotThrow(() -> { subscriberManager.addSubscriber("your-list-id", "[email protected]", "Test User"); }); } }

Conclusion

And there you have it! You've just built a solid foundation for integrating Campaign Monitor into your Java application. Remember, this is just the tip of the iceberg. The Campaign Monitor API offers a wealth of features to explore, so don't be afraid to dive deeper and experiment.

Keep coding, keep learning, and most importantly, have fun with it! If you need more information, check out the Campaign Monitor API documentation. Happy coding!