Apex Classes as REST Web Services in Salesforce




Introduction to Apex REST


Salesforce platform is amazing and its lets your create your own lightweight  REST API using Apex. You can use this REST API to access force.com data, by authenticating the caller/consumer of API using standard oAuth and return data format support JSON/XML, purely depends how you want return back the data

A few useful bits of information related to these REST APIs:
  • Use standard HTTP verbs: GET, POST, PUT, PATCH, DELETE, and HEAD.
  • You can use either HTTP or HTTPS.
  • Use standard security to authenticate your REST calls via OAuth 2.0.
  • Serialize your data in either XML or JSON format.
This is done by defining your Apex class with the @RestResource annotation to expose it as a REST resource.Similarly, add annotations to your methods to expose them through REST. For example, you can add the@HttpGet annotation to your method to expose it as a REST resource that can be called by an HTTP GET request. 

Apex REST Annotations

Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.



Apex REST Basic Code Sample


@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;
    }
}

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"
  • Replace sessionId with the <sessionId> element that you noted in the login response.
  • Replace instance with your <serverUrl> element.
  • Replace accountId with the ID of an account which exists in your organization.


Apex REST Code Sample Using RestRequest

The following sample shows you how to add an attachment to a case by using the RestRequest object. 

@RestResource(urlMapping='/CaseManagement/v1/*')
global with sharing class CaseMgmtService
{

    @HttpPost
    global static String attachPic(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Blob picture = req.requestBody;
        Attachment a = new Attachment (ParentId = caseId,
                                       Body = picture,
                                       ContentType = 'image/jpg',
                                       Name = 'VehiclePicture');
        insert a;
        return a.Id;
   }
}

Open a command-line window and execute the following cURL command to upload the attachment to a case:
curl -H "Authorization: Bearer sessionId" -H "X-PrettyPrint: 1" -H "Content-Type: image/jpeg" --data-binary @file "https://instance.salesforce.com/services/apexrest/CaseManagement/v1/caseId"
  • Replace sessionId with the <sessionId> element that you noted in the login response.
  • Replace instance with your <serverUrl> element.
  • Replace caseId with the ID of the case you want to add the attachment to.
  • Replace file with the path and file name of the file you want to attach.


Browse to http://www.hurl.it/. ADVANCE REST CLIENT / POSTMAN.
 This is a great website/app for making HTTP requests and will let us test the GET, POST, PATCH, and DELETE.

Some Useful blogs as well as reference:
http://www.wadewegner.com/2013/03/creating-anonymous-rest-apis-with-salesforce-com/
http://blogforce9.blogspot.in/2013/09/salesforce-rest-webservices-part-i.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_basic.htm









Comments

Popular posts from this blog

All about workflow rule , limitation and important points with example

All about Service Oriented Architecture : SOAP / REST differences and usage

Custom Setting in Salesforce