REST API example in Salesforce

Salesforce provides REST API to Create, Update and Delete records.

We can also define Apex as a REST Service to Create, Update and Delete records in Salesforce.

Example:

Follow the below steps

1. Create the below Apex Class

Sample Code:

@RestResource(urlMapping='/Member__c/*')
global with sharing class sampleRest
{

    @HttpDelete
    global static void doDelete()
    {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String memberId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Member__c memb = [SELECT Id FROM Member__c WHERE Id = :memberId];
        delete memb;
    }
 
    @HttpGet
    global static Member__c doGet()
    {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String memberId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Member__c result = [SELECT Id, Name FROM Member__c WHERE Id = :memberId];
        return result;
    }
 
  @HttpPost
    global static String doPost(String name)
    {
        Member__c m = new Member__c();
        m.Name = name;
        insert m;
        return m.Id;
    }
}

2. To call the doGet method from a client, open a command-line window and execute the following cURL command to retrieve an account by ID:

curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Member__c/memberId"

3. Create a file called member.txt to contain the data for the member you will create in the next step.

4. Using a command-line window, execute the following cURL command to create a new member:

curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d member.txt "https://instance.salesforce.com/services/apexrest/Member__c/"

5. Using a command-line window, execute the following cURL command to delete a member by specifying the ID:

curl —X DELETE —H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Member__c/memId"

Leave a Reply