Dynamic Endpoints with Retrofit

I’ve been working on Ward, an Android companion app for League of Legends. During development, I encountered a problem while using Riot Games’ API. Their API domain depends on the targeted region, such as North America (https://na.api.pvp.net), Western Europe (https://euw.api.pvp.net), etc.

After some StackOverflow tips here and here I found out that Retrofit is capable of supporting variable endpoint urls by implementing a custom Endpoint Class. My implementation for the League of Legends API is as follows:

public final class RiotEndpoint implements Endpoint {
private static final String PROTOCOL = “https://”;
private static final String BASE = “.api.pvp.net”;
private String url;
private String mRegion;
    public void setRegion(String region) {
mRegion = region;
url = PROTOCOL + mRegion + BASE;
}
    @Override
public String getName() {
return mRegion;
}
    @Override
public String getUrl() {
if (url == null) {
throw new IllegalStateException(“Illegal URL.”);
}
return url;
}
}

And here’s the relevant lines from my RiotClient Class:

...
private static RiotEndpoint mEndpoint = new RiotEndpoint();
...
public static RiotService getClient(String region) {
mEndpoint.setRegion(region);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(mEndpoint)
.build();
    return restAdapter.create(RiotService.class);
}
...

This allows the caller to pass in a region string that is used to construct the correct URL prior to calling the API. Here’s the client’s use in one of Ward’s fragments:

RiotClient.getClient(region)
.listSummonersByNames(region, name, this);

Hope that helps anyone that needs to conditionally hit API domains using Retrofit!