Bitly JAX-RS client, migrating from Bitly API v3 to v4
Bitly is a great Cloud service to shorten links and be more efficient on social networks. Until recently its v3 API was the main one but it is going to shut down to be replaced by v4.
As a reminder the shorten link in v3 looked like:
BitlyResponse response = target.queryParam("access_token", token)
.queryParam("longUrl", encode(toShorten))
.request(APPLICATION_JSON_TYPE)
.get(BitlyResponse.class)
with the BitlyResponse this class:
@Data
public class BitlyResponse {
private BitlyData data;
private int status_code;
@Data
public static class BitlyData {
private String url;
}
}
So to read the shorten url in v3 you just had to access url after having checked the status:
if (response.getStatus_code() != HttpURLConnection.HTTP_OK) {
throw new IllegalStateException("Bad response from bitly: " + response);
}
return response.getData().getUrl();
What you can note is that the endpoint was:
- Authorized using a query parameter,
- Using GET HTTP method
The v4 changes this by:
- Using Authorization header with a standard bearer token value,
- Using a POST,
- Requiring a group identifier,
- The request payload changed of course since we changed the HTTP method but the response one too, the shorten link i snow directly under link attribute of the response and the status code is th eplain HTTP one and no more a field.
In terms of code the new one looks like:
public String bitlyize(final String longLink, final String token, final String group) {
return target
.request(APPLICATION_JSON_TYPE)
.header("Authorization", "Bearer " + token)
.post(entity(
new BitlyData(group, "bit.ly", longLink), APPLICATION_JSON_TYPE),
BitlyResponse.class)
.getLink();
}
With the request class which looks like:
@Data
public class BitlyData {
private final String group_guid;
private final String domain;
private final String long_url;
}
And the reponse class which looks like:
@Data
public class BitlyResponse {
private String link;
// other attributes ignored
}
With this migration you should get back a functional bitly.
The last tip about this migration is that, even if the access token is simple to find in Bitly admin panel, the group uid to use can be hidden. Personally, since I had a client (this post is all about it), i just called https://api-ssl.bitly.com/v4/groups endpoint (ensure to pass your token in Authorization header) with a GET HTTP method and it contains the group uid you can directly use.
Happy coding!
From the same author:
In the same category: