Monday, 11 November 2013

Simple REST API

Below is the steps to execute the REST Code in Salesforce.


STEP 1 : 

If you are using windows environment, we have to get the CURL to be installed in your machine.

URL to install the cURL is http://www.confusedbycode.com/curl/#downloads 


STEP 2: 

Set the Remote Access in Salesforce.

Click on setup -> create->Apps. In the Connected Apps Section click on New. 






Fill all the above details and click on save. once you have saved, you will get the consumer key and consumer secret. 



STEP 3:

Generate the Access Token to execute the RESTAPI

Go to CMD and execute the following code.

curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=consumerkey" -d "client_secret=consumerSecret" -d "username=salesforceUsername" -d "password=password+securitytoken"

OUTPUT



STEP 4 : 

Create the REST API Class in Salesforce.

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

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

STEP 5:

To call the do get 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"

    Replace sessionId with the Access Token element that you will get that on STEP 3 as a result.
    Replace instance with your <serverUrl> element.
    Replace accountId with the ID of an account which exists in your organization.

OUTPUT:

{
"attributes":{
"type" : "Account",
"url" : "/services/data/v29.0/sobjects/Account/001XXXXXXX"
},
"Name" : "TEST DATA",
"Id": "001XXXXXXXXX"
}

No comments:

Post a Comment