Sending HTTP API requests with Apache Beam and Web APIs IO
If you need to send data to a third-party API, then the Web APIs IO could be a handy ally.
Disclaimer: I’m no expert on this, I’m just documenting here what I found out trying to use this IO, hoping that it could be helpful to somebody out there.
In the post, I’ll focus on examples and then add some explanation. These will all be in the same file (a JUnit 5 test class) to keep things simple. Let’s start with the entire code, and then we can slice it and explain:
implementation "org.apache.beam:beam-sdks-java-io-rrio:2.63.0"
package ...;
import com.google.api.client.http.HttpStatusCodes;
import de.gameduell.bits.pipeline.shared.util.TestPipelineExtension;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.apache.beam.io.requestresponse.*;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.util.SerializableSupplier;
import org.apache.beam.sdk.values.PCollection;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
public class WebIOTest {
@RegisterExtension
public final TestPipelineExtension testPipeline = TestPipelineExtension.create();
@Test
void runPipeline() throws IOException {
try (MockWebServer server = new MockWebServer()) {
doWithServer(server);
}
}
private void doWithServer(MockWebServer server) throws IOException {
// GIVEN A LIST OF STATUS CODES THAT THE SERVER SHOULD RETURN
List<Integer> statusCodes = List.of(
HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE,
HttpStatusCodes.STATUS_CODE_CREATED,
HttpStatusCodes.STATUS_CODE_OK,
HttpStatusCodes.STATUS_CODE_NOT_FOUND,
HttpStatusCodes.STATUS_CODE_FORBIDDEN
);
for (Integer status : statusCodes) {
// We enqueue the responses. I don't like functional API to change something from outside (like the server), that's why I'm using a for-each loop.
server.enqueue(new MockResponse().setResponseCode(status));
}
// Start the server.
server.start();
Result<String> result = testPipeline
.apply("Statuses as Source", Create.of(statusCodes.stream().map(String::valueOf).toList()))
.apply("Invoking WebAPIsIO", RequestResponseIO.of(TestCaller.of(ClientProvider.create(), server.url("/api").toString()), StringUtf8Coder.of()));
// The WebAPIsIO returns a result with two collections: responses and failures.
PCollection<String> responses = result.getResponses();
PCollection<ApiIOError> failures = result.getFailures();
// THEN
// We expect 2 successful responses and 3 failures.
PAssert.thatSingleton(responses.apply("Count Successes", Count.globally())).isEqualTo(2L);
PAssert.thatSingleton(failures.apply("Count Failures", Count.globally())).isEqualTo(3L);
testPipeline.run().waitUntilFinish();
}
// Classes
private static class TestCaller implements Caller<String, String>, SetupTeardown {
private final SerializableSupplier<CloseableHttpClient> httpClientSupplier;
private final String url;
private transient CloseableHttpClient client;
private TestCaller(SerializableSupplier<CloseableHttpClient> httpClientSupplier, String url) {
this.httpClientSupplier = httpClientSupplier;
this.url = url;
}
public static Caller<String, String> of(SerializableSupplier<CloseableHttpClient> httpClientSupplier, String url) {
return new TestCaller(httpClientSupplier, url);
}
@Override
public String call(String status) throws UserCodeExecutionException {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(status, StandardCharsets.UTF_8));
// For some reason, the SetupTeardown is not being invoked, so we need to call it manually.
// If I find out why, I can change this here.
setup();
try {
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatusCodes.STATUS_CODE_OK || statusCode == HttpStatusCodes.STATUS_CODE_CREATED) {
return status;
} else {
throw new UserCodeExecutionException("Failed with status code: " + statusCode);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setup() throws UserCodeExecutionException {
if (client == null) {
client = httpClientSupplier.get();
}
}
@Override
public void teardown() throws UserCodeExecutionException {
if (client != null) {
try {
client.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
client = null;
}
}
private static class ClientProvider implements SerializableSupplier<CloseableHttpClient> {
private static final int TIMEOUT = (int) Duration.ofSeconds(10).toMillis();
private ClientProvider() {
}
public static SerializableSupplier<CloseableHttpClient> create() {
return new ClientProvider();
}
@Override
public CloseableHttpClient get() {
return HttpClientBuilder.create()
.setDefaultRequestConfig(
RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT)
.build()
).build();
}
}
}
Necessary Ingredients:
- a Caller implementation
- a Coder implementation
- Add a RequestResponseIO to the pipeline
Caller
The Caller is what the IO will invoke for each item. It must implement the method call(I input).
A common problem with the Caller is that it might need a non-serializable client. Therefore, it is common to implement the SetupTeardown Interface, which requires providing the setup() and teardown() methods. * Note that the current implementation is not invoking these two methods — I still don’t know why.
In the example, I’ve opted to use a SerializableSupplier that provides CloseableHttpClient instances.
public class ACaller implements Caller<TheInputType, TheOutputType>, SetupTeardown {
@Override
public TheOutputType call(TheInputType input) {
// return the converted output type
// Or throw an exception
}
@Override
public void setup() {
// Your chance to startup some dependency
}
@Override
public void teardown() {
// Your chance to tear down some dependency
}
}
Coder
The coder is the good old coder from Apache Beam, since in my example I’m just receiving and giving back Strings, I just used the already available StringUtf8Coder.of(). If you need something custom, just extend the CustomCoder abstract class.
RequestResponseIO
Apply to your pipeline an instance of RequestResponseIO, which receives an instance of Caller and an instance of Coder.
RequestResponseIO.of(caller, coder)
Test Parts
I’m using JUnit 5 here. As of this writing, I could not find anything out of the shelf from Apache Beam to make the @Rule for the TestPipeline work, so the solution was to create a class that extends Pipeline and implements extends Pipeline implements BeforeEachCallback. Leave a comment if you need some help with this.
Why Use Web APIs IO?
Using the Web APIs IO is told to be an easy, efficient, and scalable way to send data to third-party APIs in Apache Beam.
Abstraction: The Caller encapsulates the call logic, keeping the code clean and organized. In the example.
Scalability: Beam automatically manages parallelism and backpressure.
Integration: RequestResponseIO integrates seamlessly with Beam's processing model.