Calling REST API in one Org from another Org

1. Write an API as per requirement & expose it.

2. Create 'CONNECTED APP' in Target Org. (Org where you have exposed API)
3. In Source Org (Org from where you are call API in Target Org), create 'REMOTE CONNECTION' of Target Org.

4. Create Apex class in Source Org to call API in Target Org.
----------------------------------------------------------------------------------------------------------------
public class AccountRestExampleConsumeFromOtherSFOrg{
    
    public String AccountRestExampleConsumeFromOtherSFOrg(){
        
        String endpoint='https://login.salesforce.com/services/oauth2/token';
        
        String username = '***********'; 
        String password = 'password+securitytoken';
        String ClientId= '************';
        String ClientSecret = '**************'; 
        
        Httprequest req = new HttpRequest();    
        req.setMethod('POST');    
        req.setHeader('Content-Type','application/x-www-form-urlencoded');
        
        req.setBody('grant_type=password&client_id=' + ClientId + '&client_secret=' + ClientSecret + '&username=' + username +'&password=' + password); 
        
        req.setEndpoint(endpoint);
        Http http = new Http();
        HttpResponse res;       
        String Access_Token;
        try {
            res = http.send(req);                
            system.debug('body:'+res.getBody());  
            JSONParser parser = JSON.createParser(res.getBody());
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
                    parser.nextToken();
                    Access_Token = parser.getText();    
                } 
            }            
        }catch(system.CalloutException e){            
            system.debug('error'+e);
        }
        Httprequest req1 = new HttpRequest();  
        req1.setEndpoint('https://{domain-name}/services/apexrest/class-name');  
        req1.setMethod('GET');    
        req1.setHeader('Content-Type','application/x-www-form-urlencoded');
        req1.setHeader('Authorization','Bearer '+Access_Token);            
        Http http1 = new Http();
        HttpResponse res1 = http1.send(req1);                 
        system.debug('body11:'+res1.getBody()); 
        return res1.getBody();
    }
}
----------------------------------------------------------------------------------------------------------------

5. Done

Comments

Popular posts from this blog

Re-Captcha in Salesforce

SF Einstein ChatBot Setup & Training

Data Loader Command Line