Can anyone will provide me example of how to get accesstoken in apex code which can be used for making rest callout?
Thanks in advance.
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityCan anyone will provide me example of how to get accesstoken in apex code which can be used for making rest callout?
Thanks in advance.
Create a connected app. Refer this link.
Copy client id and client secret from connected app you created.
There are several types of authentication. Here I used username password oauth flow.
Http h = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=XXXXXXXXXX&client_secret=YYYYYYYYY&username=yourusername&password=yourpassword');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
HttpResponse response = h.send(request);
System.debug('response '+response.getBody());
Replace "login" with "test" if you are trying in sandbox. Response will look like:
{"id":"https://login.salesforce.com/id/00Dxxxxxxxx/005xxxxxxxxx",
"issued_at":"1278448832702","instance_url":"https://yourInstance.salesforce.com/",
"signature":"xxxxxxxxxx=","access_token":
"00Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
Get access token by parsing this json response.