Skip to content

Instantly share code, notes, and snippets.

@douglascayers
Last active January 7, 2021 06:04
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save douglascayers/edd79ebe9114068b3f5a to your computer and use it in GitHub Desktop.
Salesforce apex service to make http callout to Bitly url shortener service. The .java extension is just for syntax highlighting, save them as .cls in your project.
/**
* Simple service to make http callout to Bitly url shortener service.
*/
public class BitlyService {
/**
* Given a long URL will return the shortened version.
* https://dev.bitly.com/api-reference#createBitlink
*/
public String shorten(String url) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Bitly/v4/shorten');
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer {!$Credential.Password}');
req.setHeader('Accept', 'application/json');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'group_guid' => '{!$Credential.UserName}',
'long_url' => url
}));
HttpResponse res = new Http().send( req );
Map<String, Object> response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) response.get('link');
}
}
@douglascayers
Copy link
Author

@douglascayers
Copy link
Author

Code updated to use Bitly's API v4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment