REST API example in Salesforce

Representational State Transfer (REST) is a style of software architecture for distributed systems such as the World Wide Web. REST has emerged as a predominant web service design model.

REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources.

The Force.comREST API provides you with a powerful, convenient, and simple Web services API for interacting with Force.com. Its advantages include ease of integration and development, and it is an excellent choice of technology for use with mobile applications and Web 2.0 projects. However, if you have large numbers of records to process, you may wish to use Bulk API, which is based on REST principles and optimized for large sets of data.

Example:

Follow the below steps

1. Create the below Apex Class

@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/Account/accountId"

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/Account/memId"

No comments:

Post a Comment