Saturday 23 March 2024

Say Goodbye to Boilerplate: Annotating Your Way to Powerful API Clients

Ever feel like writing boilerplate code for every single REST API call?

Constructing URLs, managing parameters, setting headers, crafting bodies - it's all time-consuming and repetitive. Wouldn't it be amazing if, like ORMs for databases, there was a way to simplify API interactions?

Well, you're in luck!

This post will introduce you to the concept of annotation-based RPC clients, a powerful tool that can dramatically reduce your API coding burden. We'll explore how annotations can automate the tedious parts of API calls, freeing you to focus on the real logic of your application.

I will use search engine API as example to demonstrate how it will look like.

public interface GoogleSearchService {

@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey,
                                @XQuery("cx") String context,
                              @XQuery(value = "q", encoded = true) String searchTerm);


This approach uses annotations to declaratively specify everything about the API call. This declarative style offers several advantages:

  • Familiar Programming Experience: The syntax feels like you're interacting with a normal programming API, making it intuitive and easy to learn.
  • Abstraction from Implementation Details: You don't need to worry about the internal names of parameters or the specifics of the underlying protocol. The annotations handle those details for you.
  • Simplified Error Handling: The RpcReply abstraction encapsulates error handling, providing a clean and consistent way to manage potential issues.
  • Seamless Asynchronous Support: Adding asynchronous execution becomes straightforward, allowing you to make non-blocking API calls without extra effort.
  • Enhanced Testability: Everything related to the API interaction is defined through the interface, making unit testing a breeze. You can easily mock the interface behavior to isolate your application logic.

Lets have look at RpcReply abstraction 

public interface RpcReply<T> {

T value();
void execute();
int statusCode();
boolean isSuccess();
Optional<String> reply();
Optional<String> error();
Optional<Exception> exception();

The RpcReply object plays a crucial role in this approach. It's a lazy object, meaning its execution is deferred until explicitly requested. This allows you to choose between synchronous or asynchronous execution depending on your needs.

More importantly, RpcReply encapsulates error handling. It takes care of any errors that might occur during the actual API call. You can access the response data or any potential errors through a clean and consistent interface provided by RpcReply. This eliminates the need for manual error handling code within your application logic.

One more thing is missing, reply using map is not neat, it will be better if it is strongly type object like Searchresult.

In essence, using strongly typed objects provides a cleaner, more reliable, and more maintainable way to work with API responses.

Lets add StrongType to our API, it will look something like this.

public interface GoogleSearchService {

@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey,
    @XQuery("cx") String context,
     @XQuery(value = "q", encoded = true) String searchTerm);

@XHeaders({"Content-Type: application/json"})
RpcReply<GoogleSearchResult> find(@XQuery("key") String apiKey,
    @XQuery("cx") String context,
    @XQuery(value = "q", encoded = true) String searchTerm);


Let's dive into how we can write code that interprets declarative definitions and translates them into actual HTTP API calls.

There are several approaches to generate the code behind this interface:

  • Build Plugin: This method utilizes a build plugin to generate actual code during the compilation process.
  • Dynamic Proxy: This approach employs a dynamic proxy that can leverage the provided metadata to generate real API calls at runtime.

Many frameworks leverage either of these options, or even a combination of both. In the solution I'll share, we'll be using Dynamic Proxy.

I have written about dynamic proxy in past, you can read this if new to concept or need refresher



High Level Sketch of implementation

In this step, we create a proxy object. This proxy will act as an intermediary between the client application and the real server. It can intercept all outgoing calls initiated by the client app.

During this stage, the client interacts with a remote proxy object. This proxy acts as a transparent intermediary, intercepting all outgoing calls.

Here's what the proxy does:

  • Builds metadata: The proxy can gather additional information about each call, such as timestamps, user IDs, or call identifiers. This metadata can be valuable for debugging, logging, or performance analysis.
  • Makes the server call: Once it has the necessary information, the proxy forwards the request to the actual server.
  • Handles errors: If the server call encounters any issues, the proxy can gracefully handle the error and provide a meaningful response back to the client.
  • Parses the response: The proxy can interpret the server's response and potentially transform it into a format that's easier for the client to understand. This can include type safety checks to ensure the returned data matches the expected format.

Code snippet that build Rpc Stack Trace

HttpCallStack callStack = new HttpCallStack(builder.client());
_processMethodTags(method, callStack);
_processMethodParams(method, args, callStack);
callStack.returnType = returnTypes(method);
return callStack;

Full code of proxy is available at

Lets look at few examples of client service interface.

public interface DuckDuckGoSearch {
@XHeaders({"Content-Type: application/json"})
RpcReply<List<Map<String, Object>>> suggestions(@XQuery(value = "q", encoded = true) String searchTerm);

@XHeaders({"Content-Type: application/json"})
RpcReply<String> search(@XQuery(value = "q", encoded = true) String searchTerm);


public interface DuckDuckGoService {
@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("api_key") String apiKey, @XQuery("engine") String engine, @XQuery(value = "q", encoded = true) String searchTerm);

@XHeaders({"Content-Type: application/json"})
RpcReply<DuckDuckGoSearchResult> query(@XQuery("api_key") String apiKey, @XQuery("engine") String engine, @XQuery(value = "q", encoded = true) String searchTerm);

public interface GoogleSearchService {

@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey, @XQuery("cx") String context, @XQuery(value = "q", encoded = true) String searchTerm);

@XHeaders({"Content-Type: application/json"})
RpcReply<GoogleSearchResult> find(@XQuery("key") String apiKey, @XQuery("cx") String context, @XQuery(value = "q", encoded = true) String searchTerm);


Client code is very lean, it looks something like this

RpcBuilder builder = new RpcBuilder().serviceUrl("");
GoogleSearchService service = builder.create(GoogleSearchService.class);

String key = System.getenv("google_search");

RpcReply<Map<String, Object>> r =, "61368983a3efc4386", "large language model");
Map<String, Object> value = r.value();
List<Map<String, Object>> searchResult = (List<Map<String, Object>>) value.get("items");

searchResult.forEach(v -> {
System.out.println(v.get("title") + " -> " + v.get("link"));

RpcReply<GoogleSearchResult> searchResults = service.find(key, "61368983a3efc4386", "large language model");



Full client code is available @


Dynamic proxies offer a powerful approach to abstraction, providing several benefits:

  • Protocol Independence: The underlying communication protocol can switch from HTTP to something entirely new (e.g., gRPC, custom protocols) without requiring any changes to the client code. The dynamic proxy acts as an intermediary, insulating the client from the specifics of the protocol being used.
  • Enhanced Functionality: Dynamic proxies can add valuable features to client interactions. This can include:
    • Caching: The proxy can store responses to frequently accessed data, reducing load on the server and improving performance.
    • Throttling: The proxy can limit the rate of calls made to the server to prevent overloading or comply with usage quotas.
    • Telemetry: The proxy can collect data about client-server interactions, providing insights into system performance and user behavior.

By leveraging dynamic proxies, you can achieve a clean separation between the client's core logic and the communication details. This promotes loose coupling, making your code more adaptable, maintainable, and easier to test.

This approach leads us towards a concept similar to API Relational Mapping (ARM) (though this term isn't widely used). Think of it as a specialized layer that translates between API calls and the underlying functionalities they trigger.

Full client library is available @ rpcclient.

No comments:

Post a Comment