Step 1: Create a apex class with all the fields required in REST request.
global class LeadInfoParser {
global String LastName{get;set;}
global String FirstName{get;set;}
global String Company{get;set;}
global String email{get;set;}
global String Phone{get;set;}
global String LeadStatus{get;set;}
}
Step 2:To declare a class as a custom endpoint, you only need to annotate a global class with “@RestResource” and define the name of the endpoint.
In the below example, REST Service endpoint will be
https://salesforcehostname/services/apexrest/LeadService
@RestResource(urlMapping='/LeadService/*')
global without sharing class LeadService {
@HttpPost
global static String createLead(LeadInfoParser leadrec){
Lead leadObj = new Lead();
leadObj.FirstName =leadrec.FirstName;
leadObj.LastName=leadrec.LastName;
leadObj.Phone=leadrec.Phone;
leadObj.email=leadrec.email;
leadObj.Company = leadrec.Company;
leadObj.Status = leadrec.LeadStatus;
Database.saveResult saveResult = database.insert(leadObj,false);
if(saveResult.isSuccess()){
System.debug('Record Id:'+saveResult.getId());
}
else{
System.debug('saveResult:'+saveResult.getErrors());
}
//Response
JSONGenerator gen=JSON.createGenerator(true);
gen.writeStartObject();
gen.writeStringField('message','Lead record is created Successfully');
gen.writeEndObject();
String responseString= gen.getAsString();
return responseString;
}
}
REST Service is now ready with these two simple steps. We can quickly test this REST service using workbench.developerforce.com.
Request Body:
{"leadrec":{
"FirstName":"Laxman",
"LastName":"Vattam",
"Company":"Google",
"LeadStatus":"Open",
"email":"laxmanVattam@gmail.com",
"Phone":"+1123456"
}
We can use @HttpGet similar to @HttpPost example above.
Developers can tailor the REST API to suit the business needs of their application. An endpoint can be defined with an Apex Class using the @RestResource annotation, and the method annotations allow the endpoint to behave specifically for creating, updating, deleting and querying data within the instance.
No comments:
Post a Comment