Sunday, 15 December 2024

REST apex code fetch the API usage

 Apex code fetch the API usage


public class ApexAPIUsageMonitor {
public static void fetchApiUsage() {
String endpoint = System.Url.getOrgDomainUrl().toExternalForm() + '/services/data/v62.0/limits';
// Set up HTTP request
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
try {
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
// Parse the API response
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
System.debug('API Usage Details: ' + result.get('DailyApiRequests'));
} else {
System.debug('Failed to fetch API usage. Status: ' + res.getStatusCode());
}
} catch (Exception e) {
System.debug('Error fetching API usage: ' + e.getMessage());
}
}
}