Back

Step by Step Guide to Building an Affinity API Integration in Java

Aug 18, 20248 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Affinity API integration? You're in for a treat. Affinity's API is a powerful tool that'll let you tap into their relationship intelligence platform. In this guide, we'll walk through building a robust integration in Java. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got:

  • A Java development environment (I'm assuming you're all set here)
  • An Affinity API key (grab one from your Affinity account)
  • Your favorite HTTP client library (we'll use OkHttp in this guide)

Setting up the project

First things first, let's get our project set up:

  1. Create a new Java project in your IDE of choice.
  2. 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

Alright, let's get authenticated! Affinity uses API key authentication, so we'll create a base client class:

import okhttp3.OkHttpClient; import okhttp3.Request; public class AffinityClient { private final OkHttpClient client; private final String apiKey; private static final String BASE_URL = "https://api.affinity.co/"; public AffinityClient(String apiKey) { this.apiKey = apiKey; this.client = new OkHttpClient(); } protected Request.Builder getRequestBuilder() { return new Request.Builder() .header("Authorization", "Basic " + apiKey); } // We'll add more methods here later }

Making API requests

Now that we're set up, let's make some requests! We'll add methods to our AffinityClient class:

import okhttp3.Response; public Response get(String endpoint) throws IOException { Request request = getRequestBuilder() .url(BASE_URL + endpoint) .build(); return client.newCall(request).execute(); } public Response post(String endpoint, RequestBody body) throws IOException { Request request = getRequestBuilder() .url(BASE_URL + endpoint) .post(body) .build(); return client.newCall(request).execute(); }

Implementing key Affinity API endpoints

Let's implement some key endpoints. We'll focus on Persons for this example:

public class PersonsApi extends AffinityClient { public PersonsApi(String apiKey) { super(apiKey); } public Response getPerson(int personId) throws IOException { return get("persons/" + personId); } public Response createPerson(String firstName, String lastName) throws IOException { RequestBody body = new FormBody.Builder() .add("first_name", firstName) .add("last_name", lastName) .build(); return post("persons", body); } }

Error handling and rate limiting

Let's add some error handling and respect Affinity's rate limits:

public Response makeRequest(Request request) throws IOException { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } // Check rate limit headers String remaining = response.header("X-RateLimit-Remaining"); if (remaining != null && Integer.parseInt(remaining) < 10) { // Consider implementing a delay or queueing mechanism here } return response; }

Data mapping and models

To make our lives easier, let's create a simple Person model:

public class Person { private int id; private String firstName; private String lastName; // Getters and setters omitted for brevity }

And a method to map API responses to our model:

import com.fasterxml.jackson.databind.ObjectMapper; public Person mapToPerson(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, Person.class); }

Building a simple use case

Let's put it all together with a simple example:

PersonsApi api = new PersonsApi("your-api-key"); // Create a new person Response createResponse = api.createPerson("John", "Doe"); Person newPerson = mapToPerson(createResponse.body().string()); // Get the person we just created Response getResponse = api.getPerson(newPerson.getId()); Person retrievedPerson = mapToPerson(getResponse.body().string()); System.out.println("Created and retrieved: " + retrievedPerson.getFirstName() + " " + retrievedPerson.getLastName());

Testing the integration

Don't forget to test! Here's a simple JUnit test to get you started:

import org.junit.Test; import static org.junit.Assert.*; public class PersonsApiTest { @Test public void testCreateAndGetPerson() throws IOException { PersonsApi api = new PersonsApi("your-test-api-key"); Response createResponse = api.createPerson("Test", "User"); Person newPerson = mapToPerson(createResponse.body().string()); Response getResponse = api.getPerson(newPerson.getId()); Person retrievedPerson = mapToPerson(getResponse.body().string()); assertEquals(newPerson.getId(), retrievedPerson.getId()); assertEquals("Test", retrievedPerson.getFirstName()); assertEquals("User", retrievedPerson.getLastName()); } }

Best practices and optimization

To take your integration to the next level:

  1. Implement caching to reduce API calls
  2. Use batch operations where possible
  3. Handle pagination for large data sets
  4. Implement robust error handling and logging

Conclusion

And there you have it! You've just built a solid foundation for your Affinity API integration in Java. From here, you can expand to cover more endpoints, implement more complex operations, and really make the most of what Affinity has to offer.

Remember, the key to a great integration is understanding the API documentation, respecting rate limits, and building with scalability in mind. Happy coding, and may your relationships always be intelligently managed!