0

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.

1 Answer 1

2

Create a connected app. Refer this link.

https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_defining_remote_access_applications.htm

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.