I'm new in Apex and we have requirement, I need to send a record from salesforce to external system using Rest API whenever a record is created in Salesforce, I need to send couple of SF fields to external system along with External system required fields. I created a class which has both Json generaotor and Http post method however this code is working with only one record, I'm not sure how to create a list of records to so that when user creates a record in Salesforce, only that record should go to external system.
Apex class
public class RadarUpdate {
@future (callout=true)
public static void postcallout(string id) {
Patient_Satisfaction__c c = [select id, Name, Reporter_First_Name__c, Reporter_Last_Name__c,
Reporter_Phone__c, Description_of_Feedback__c from Patient_Satisfaction__c] ;
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeObjectField('First name ', c.Reporter_First_Name__c);
gen.writeObjectField('Last name',c.Reporter_Last_Name__c);
gen.writeObjectField('Phone',c.Reporter_Phone__c);
gen.writeObjectField('description',c.Description_of_Feedback__c);
gen.writeObjectField('Name',c.Name);
gen.writeObjectField('incident_group_id',7387);
gen.writeEndObject();
String jsonS = gen.getAsString();
System.debug('jsonMaterials'+jsonS);
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.radarfirst.com/incidents');
request.setMethod('POST');
request.setHeader('Content-Type','application/json;charset=UTF-8');
request.setHeader('User-agent', 'Salesforce-integration-client');
request.setHeader('Authorization','Bearer abc');
request.setBody(jsonS);
// Set the body as a JSON object
HttpResponse response = http.send(request);
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
}
}
Best Answer
You can use gen.writeStartArray() and gen.writeEndArray() to create an array and then write list of objects.
Sample Code