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
priyanka m 8priyanka m 8 

How to call service now api's in salesforce and map the fields between incident and case

I want to integrate servicenow and salesforce. I am able to create the incident from salesforce from apex class. But I want to create the incident in servicenow when case is created in salesforce.
How this can be achieved?
kumar_arunkumar_arun
Hi Priyanka,

You can write Apex trigger on case object, that trigger will call an Apex class, which will then create an 'Incident' in ServiceNow. Something like the code given below.
trigger CreateIncidentInServiceNow on Case (after insert) {
  for(Case c : Trigger.New){                                                  
  ServiceNowPostRequest.servicenowPostMethod(c.id);                                                                          
  }
}

public class ServiceNowPostRequest{
    
       @future(callout=true)
        public static void servicenowPostMethod(string incidentCase){  
        
        Http http = new Http();
        HttpRequest req =  new HttpRequest();
        HttpResponse res = new HttpResponse();
        
        String username = 'xxxxx';
        String password = 'xxxxxxxxxxxxx';
        
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'BASIC ' +
        EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        
        req.setEndpoint('https://Your Instance/api/now/v1/table/incident');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartObject();
        
        Case c=[select Description from case where id=: incidentCase];
        gen.writeStringField('number', c.id);
        gen.writeStringField('caller_id','Alene Rabeck');
        gen.writeStringField('short_description', c.description);
        gen.writeEndObject();
        
        //you can now use String pretty as your body
        String jsonBody = gen.getAsString();
        
        req.setBody(jsonBody);
        res = http.send(req);
        
        system.debug(res.getBody());
        }
            

}

Mark Best Answer if this fulfills your requirement.
Bhojraj DhakateBhojraj Dhakate

Hi Arun,

I am new to salesforce. I am trying to integrate salesforce to servicenow.

I have created "APEX Class and the APEX trigger" as mentioned in your thread.

When i am trying to ececute the code i am getting "Unexpected token trigger error".

Am i doing something wrong ? Can you help me on that?

Thanks in advance!

Thanks,
Bhojraj Dhakate