Search code examples
javasalesforceapexsalesforce-service-cloud

How to get the access_token first in Apex Restful service to call GET/POST methods from outside?


I am doing Salesforce trailhead from the link : https://trailhead.salesforce.com/modules/apex_integration_services/units/apex_integration_webservices.

In this tutorial they've use access_token to call the GET request. But they have not guided us how to get the access_token, which is an important steps to call the APEX Rest from outside.

enter image description here

I tied to do something like below its saying me the error:

https://ap5.salesforce.com/services/oauth2/token?client_id="3MVG9d8..z.hDcPJZPIzGJ5UZDuKCOqbH8CCGCPnmwQuRbwLZ_2f.thbqWMX82H7JRGx4
6VYyEkuwzQ9._ww5"&client_secret="1180508865211885204"&username="pXXXXXXXXXXXXXXX.com"&password="AgXXXXXXXX"&grant_type=password

enter image description here


Solution

  • I understood the concept now and thanks for sharing other links.

    client_id, client_secret, username, password and grant_type should be sent in a HTTP POST body not in header.

    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setHeader('Content-Type','application/x-www-form-urlencoded');
    req.setEndpoint('https://ap5.salesforce.com/services/oauth2/token');
    
    String CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
    String CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX';
    String USERNAME = 'XXXXXXXXXXXXXX';
    String PASSWORD = 'XXXXXXXXXXXXXX';
    
    req.setBody('grant_type=password' + '&client_id='+CLIENT_ID + 
                '&client_secret='+CLIENT_SECRET + '&username='+USERNAME + '&password='+PASSWORD);
    
    Http http = new Http();
    HTTPResponse response = http.send(req);
    System.debug('Body ' + response.getBody());
    System.debug('Status ' + response.getStatus());
    System.debug('Status code ' + response.getStatusCode());