Skip to content

Instantly share code, notes, and snippets.

/runAPI Secret

Created Dec 17, 2017
Embed
What would you like to do?
public static List<sfLimit> runAPI(){
//Get a token
String clientId = Label.Limits_Connected_App_Client;
String clientSecret = Label.Limits_Connected_App_Key;
String username= Label.Limits_Username;
String password= Label.Limits_PW;
//using this request body we'll make API call
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
String sfdcURL = URL.getSalesforceBaseUrl().toExternalForm();
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
String endpoint = Utilities.isProduction() ? 'https://login.salesforce.com/services/oauth2/token' : 'https://test.salesforce.com/services/oauth2/token';
system.debug(endpoint);
req.setEndpoint(endpoint);
HttpResponse res = h.send(req);
OAuth2 objAuthInfo =(OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
system.debug(objAuthInfo);
String restAPIURL = sfdcURL + '/services/data/v41.0/limits';
HttpRequest httpRequest = new HttpRequest();
httpRequest.setMethod('GET');
httpRequest.setHeader('Authorization', 'Bearer ' + objAuthInfo.access_token);
httpRequest.setEndpoint(restAPIURL);
List<sfLimit> l = new List<sfLimit>();
String response = '';
try {
Http http = new Http();
HttpResponse httpResponse = http.send(httpRequest);
if (httpResponse.getStatusCode() == 200 ) {
String JSONContent = httpResponse.getBody();
System.debug(JSONContent);
JSONParser parserJira = JSON.createParser(JSONContent);
String lName;
String innerName;
Integer Max;
Integer Remaining;
String text;
Integer innerMax;
Integer innerRemaining;
while (parserJira.nextToken() != null) {
if (parserJira.getCurrentToken() == JSONToken.FIELD_NAME) {
Max = null;
Remaining = null;
lName = null;
text = parserJira.getText();
lName = text;
if (parserJira.nextToken() != JSONToken.VALUE_NULL) {
if (text == 'Max') {
Max = parserJira.getIntegerValue();
} else if (text == 'Remaining') {
Remaining = parserJira.getIntegerValue();
} else {
//inner Limits
if(parserJira.nextToken() != JSONToken.END_OBJECT){
if(parserJira.getText() == 'Max'){
parserJira.nextToken();
innerMax = parserJira.getIntegerValue();
parserJira.nextToken();
}
if(parserJira.getText() == 'Remaining'){
parserJira.nextToken();
innerRemaining = parserJira.getIntegerValue();
}
}
Max = innerMax;
Remaining = innerRemaining;
consumeObject(parserJira);
}
}
}
sfLimit sfl = new sfLimit(text,Max,Remaining);
system.debug(sfl);
l.add(sfl);
}
system.debug(l);
return l;
} else {
System.debug(' httpResponse ' + httpResponse.getBody() );
throw new CalloutException( httpResponse.getBody() );
return null;
}
} catch( System.Exception e) {
System.debug('ERROR: '+ e);
throw e;
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment