function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ArunaAruna 

Expose APEXT REST Webservices to external system when records is updating(trigger)

Hello there,

I am having below requirement.
In salesforce when a record is updated then send data of that record to external system using reset API JSON file.
I have written below code but I am not sure whether I am going in right direction 

Trigger

rigger ImplementationPlanActivity on Implementation_Plan_Activity__c (after update) {
    Trigger_Settings__c triggerSettings = Trigger_Settings__c.getInstance();
    if(triggerSettings.ImplementationPlanActivity__c == false){
        return;
    }
            set<Id> IPAIdSet=new Set<Id>();
            for(Implementation_Plan_Activity__c IPArecord : trigger.new ){
                IPAIdSet.add(IPArecord .id);
            }
            IPAResetAPIClass.IPAData(IPAIdSet);

        }
    }
Webservice class

global class IPAResetAPIClass{
@future(callout=true)
    global static void IPAData(Set<Id> newIPASetId){
    
        List<Implementation_Plan_Activity__c> ipaNewList=[SELECT id,Name,
                                                                    Account_Manager__r.Name,
                                                                    Account_Manager__r.Email,
                                                                    Account_Specialist__r.Name,
                                                                    Account_Specialist__r.Email,    
                                                                    SFID18__c ,
                                                                    RecordTypeId
                                                            FROM Implementation_Plan_Activity__c where Id IN : newIPASetId];
        
        List<impWarpperClass> warpperIPAList=new List<impWarpperClass>();
        
            warpperIPAList.add(new impWarpperClass(ipaNewList[0].id,
                                                    ipaNewList[0].Name,
                                                    ipaNewList[0].Account_Manager__r.Name,
                                                    ipaNewList[0].Account_Manager__r.Email,
                                                    ipaNewList[0].Account_Specialist__r.Name,
                                                    ipaNewList[0].Account_Specialist__r.Email,
                                                    ipaNewList[0].SFID18__c,
                                                    ipaNewList[0].RecordTypeId));
        
 
       RecordType recordTypeRecord=[Select id,Name from RecordType  where id=:ipaNewList[0].RecordTypeId limit 1];
       
       string  resource=null;
       if(recordTypeRecord.Name=='Auto Provisioning'){
           resource='Auto Provisioning';
       }
       else if(recordTypeRecord.Name =='Workbook'){
           resource='Workbook';
        }      
        system.debug('*********warpperIPAList='+warpperIPAList);
        
        string JSONString=JSON.serializePretty(warpperIPAList);
        system.debug('*********serialized imp='+JSONString);
        
        string endURL;
        
        endURL=geURL+resource+'/'+ipaNewList[0].id;
        system.debug('*********endURL='+endURL);
        HttpRequest req=new HttpRequest();
        //Set HttpRequest Method
        req.setMethod('POST');
      
        req.setHeader('content-type', 'application/json');
        //Set HTTPRequest Endpoint dummy url
        req.setEndpoint('http://requestb.in/13auzf41');
        //req.setEndpoint(endURL);
        
        //Set HTTP Request Body
        req.setBody(JSONString);
        Http http = new Http();
        try{
            HTTPResponse res = http.send(req);
            //Helpful debug messages
            System.debug(res.toString());
            System.debug('STATUS:'+res.getStatus());
            System.debug('STATUS_CODE:'+res.getStatusCode());
            System.debug('Content: ' + res.getBody());
            
            //we can create success object record
        }
        catch(Exception e){
            System.debug('******* error message='+e);
            //we can create error object record
        }
    
    }
    
    global class impWarpperClass{
    
        global string IPAId{get;set;}
        global string IPAName{get;set;}   
        global string IPAAccManagerName{get;set;}   
        global string IPAAccManagerEmail{get;set;} 
        global string IPAAccSpecialListrName{get;set;}   
        global string IPAAccSpecialListEmail{get;set;} 
           
        global string IPASFDCId{get;set;}
        global string IPARecordTypeId{get;set;}
        
        global impWarpperClass(string IPAId,string IPAName,
                                        string IPAAccManagerName,
                                        String IPAAccManagerEmail,
                                        string IPAAccSpecialListrName,
                                        string IPAAccSpecialListEmail,
                                        string IPASFDCId,
                                        string IPARecordTypeId){
            this.IPAId=IPAId;
            this.IPAName=IPAName;
            this.IPAAccManagerName=IPAAccManagerName;
            this.IPAAccManagerEmail=IPAAccManagerEmail;
            this.IPAAccSpecialListrName=IPAAccSpecialListrName;
            this.IPAAccManagerEmail=IPAAccSpecialListEmail;
            this.IPASFDCId=IPASFDCId;
            this.IPARecordTypeId=IPARecordTypeId;
            
        }
       
    }
  
       }

}
am I going right dirction. is this correct way to send data from salesforce to external system using rest api JSON file.
If I am wrong can any please let me know how can I expose salesforce data to external system when records is updted in salesforce.
Thank you.
Chris Gary CloudPerformerChris Gary CloudPerformer
The basic Idea of calling a @future method to send the data seems to be the correct approach for this requirement.  As long as other code is developed properly in this instance, and doesn't call updates on Implementation_Plan_Activity__c in a loop - you should be fine.  Otherwise that type of code (other than being badly written) may cause you to exceed your limit of 50 future invocations in a single context.

Please remember to mark a comment as best answer (even if its not this one). This marks the thread as solved and helps the community!
ArunaAruna
Hi Chris,

Thank you for replay,

while I am trying hit the external server I am getting below error

Content:     {"status":{"code":400,"errorId":"Fail","userMessage":"Missing required parameter","detailsMessage":"salesforceUserEmail is required","apiVersion":"v1"},"data":{}}

How can send salesforce email id.

String authorize='teste@test.com';
        
        HttpRequest req=new HttpRequest();
        //Set HttpRequest Method
        req.setMethod('POST');
        //Set HTTPRequest header proporties
          req.setHeader('Authorization',authorize);
        req.setHeader('content-type', 'application/json');
       
        req.setEndpoint(endURL);

 
Chris Gary CloudPerformerChris Gary CloudPerformer
This is not an error generated in your Salesforce code - so clearly you are creating the body content, wrapping it in a Request, and sending it correctly. Evidently, according to the details of the message you shared, this is a requirement of the Web Service you are communicating with.  I do not know what service you are communicating with, nor what their requirements are for the data structure of the JSON data you are sending them. Do you have an example of what the correct JSON output should look like? Perhaps we can help you determine it from there.
ArunaAruna
Hi Chris,

Thank you for your response I am getting different error now 

Unable to tunnel through proxy. Proxy returns "HTTP/1.0 403 Forbidden"

I did setup remote server and I did included endpoint url in the code .
Apart from end point url and remote site settings do I need to do any other settings?
Do I need to create any certificate in salesforce and give to external system ?

Can you please help me to resolve this issue?
 
Chris Gary CloudPerformerChris Gary CloudPerformer
Apologies for the delay in response.  It sounds like there is a proxy server the service sits behind that is not allowing communication.  Once again, this isn't specifically a Salesforce issue, but instead something you may need to work through with the provider, perhaps getting the Salesforce IP Addresses whitelisted, or providing some additional authorization header within your request.