I think the reason there is no easy way is that an org actually supports many versions. So we really want the newest. I wrote this code:
public class VersionResponse
{
public String label;
public String url;
public String version;
}
public static String getNewestAPIVersion()
{
String url = 'https://' + ApexPages.currentPage().getHeaders().get('Host') + '/services/data';
system.debug('Url: ' + url);
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(url);
req.setHeader('Content-Type', 'application/json');
Http http = new Http();
HTTPResponse resp = http.send(req);
String json = resp.getBody();
system.debug('Body: ' + json);
List<VersionResponse> parsedList = (List<VersionResponse>)System.JSON.deserialize(json, List<VersionResponse>.class);
system.debug('Parsed Body: ' + parsedList);
String latestVersion = '0';
for (VersionResponse item : parsedList)
{
if (latestVersion.compareTo(item.version) < 0)
{
latestVersion = item.version;
}
}
system.debug('Latest Version: ' + latestVersion);
return latestVersion;
}
If you do this, you must open up the host in each org. Go to Setup > Security Controls > Remote Site Settings, and add an entry for the host.
If you use communities, you will need to add the community prefix to the URl based on the user. Since your community uses a different host name, a Remote Site Setting must be added for it to.
list<Network> Prefix = [SELECT Id, UrlPathPrefix FROM Network WHERE Name = :community Limit 1];
string prefix = Prefix[0].UrlPathPrefix;
String url = 'https://' + ApexPages.currentPage().getHeaders().get('Host') + '/' + prefix + '/services/data';