How to get Salesforce Access Token and execute SOQL using Apex?

How to get Salesforce Access Token and execute SOQL using Apex?

1. Add the Salesforce My Domain URL in your Remote Site Settings in Setup in the Source org.

Remote Site Setting:

2. Create a Connected app in the target org. Make a note of the Consumer Key and Secret.

Sample Code:

HttpResponse response = new HttpResponse();
HttpRequest req = new HttpRequest();
Http objHttp = new Http();
String strEndPoint = '{YOUR_DOMAIN_URL}';
String strUsername = '{YOUR_USERNAME}';
String strPassword = '{YOUR_PASSWORD}';
String strClientId = '{YOUR_CONNECTED_APP_CONSUMER_KEY}';
String strClientSecret = '{YOUR_CONNECTED_APP_CONSUMER_SECRET}';  
String strBody = 'username=' + strUsername;
strBody += '&password=' + strPassword;
strBody += '&client_id=' + strClientId;
strBody += '&client_secret=' + strClientSecret;
strBody += '&grant_type=password';
req.setHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
req.setBody( strBody);
req.setEndpoint( 
	strEndPoint + '/services/oauth2/token' 
);
req.setMethod( 'POST');
response = objHttp.send( req );
System.debug(
    'Access Token Response is ' + response
);
if ( response.getStatusCode() == 200 ) {            
        
    Map < String, Object > resultMap = ( Map< String, Object> )JSON.deserializeUntyped( response.getBody() );
    String strAccessToken = ( String )resultMap.get( 'access_token' );
    
    System.debug(
        'Access Token is ' + strAccessToken
    );
		
	req = new HttpRequest();
	req.setHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
	req.setHeader( 'Authorization', 'Bearer ' + strAccessToken );
	req.setEndpoint( 
		strEndPoint + 
		'/services/data/v53.0/query' 
		+ '/?q=SELECT+Name+FROM+Account+WHERE+Id+=+\'0013t00002XXRyDAAX\''
	);
	req.setMethod( 'GET');
	response = objHttp.send( req );
    System.debug(
        'SOQL Response is ' + response
    );
	
	if ( response.getStatusCode() == 200 ) {            
    
		System.debug( 
			'Response Body is ' + response.getBody() 
		);
	
	}
    
}

Output:

In the Debug Logs, access_token is “SESSION_ID_REMOVED” since in the Debug Logs, we cannot print the Access Token to check it’s value.

Leave a Reply