WebServices in salesforce


REST (Representational state transfer):

REST is over HTTP and SOAP can be over any transport protocol like HTTP, FTP, …
Basically REST will return the information In any way like string, xml, html or json ..any type
REST is a simple frame work
No WSDL frame work is required for this.
It can give human readable result or simple to read the result.
We can do CRUD operations with REST (Create, read, Update and Delete) on source.

REST service consuming in salesforce:
In this example I am going to explain with open weather service

HttpRequest hr=new HttpRequest();
     hr.setEndpoint('http://api.openweathermap.org/data/2.5/find?q=hyderabad,india&mode=xml');
     hr.setMethod('GET');
     http htp=new http();   
     HTTPResponse res=htp.send(hr); 

Response is like below XML:
<?xml version="1.0" encoding="utf-8"?>
<cities>
  <calctime>0.2123</calctime>
  <count>1</count>
  <mode>name</mode>
  <list>
    <item>
      <city id="1269843" name="Hyderabad">
        <coord lon="78.474442" lat="17.37528"/>
        <country>IN</country>
        <sun rise="2014-06-12T00:11:18" set="2014-06-12T13:20:42"/>
      </city>
      <temperature value="310.7" min="309.15" max="312.15" unit="kelvin"/>
      <humidity value="26" unit="%"/>
      <pressure value="1006" unit="hPa"/>
      <wind>
        <speed value="7.7" name="Moderate breeze"/>
        <direction value="260" code="W" name="West"/>
      </wind>
      <clouds value="40" name="scattered clouds"/>
      <precipitation mode="no"/>
      <weather number="802" value="scattered clouds" icon="03d"/>
      <lastupdate value="2014-06-12T09:40:00" unix="1402566000"/>
    </item>
  </list>
</cities>

Response in JSON:
{"message":"accurate","cod":"200","count":1,"list":[{"id":1269843,"name":"Hyderabad","coord":{"lon":78.474442,"lat":17.37528},"main":{"temp":311.39,"pressure":1005,"humidity":25,"temp_min":310.15,"temp_max":312.15},"dt":1402567800,"wind":{"speed":7.7,"deg":280},"sys":{"country":"IN"},"rain":{"3h":0},"clouds":{"all":40},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}]}]}
About GET and POST
GET is to request data from specific resource that’s means it will send an request to get some data
POST: submit data to be processed on resource.
GET: request will be passed on URL
POST: request information will passed in body
GET: Length restriction
POST: NO length of data restriction
GET: less secure
POST: more secure

  REST service exposing from salesforce:
(https://c.ap1.visual.force.com/apex/callerPage)
We can expose service by using salesforce REST.
1.                   We need a class with keyword "@RestResource" to signify the class responsible for handling HTTP requests and act as REST based web service. Make sure the class has global access specifier.
2.                   The urlMapping  property allows us to set path where the service will be available. This is process of setting up the endpoint for service. Example:                                                                             https://.salesforce.com/services/apexrest/showAccounts
3.                   Include @HttpGet keyword before method name for denoting a method to respond on a HTTP GET request; include @HttpPost  keyword before method name for denoting a method to respond on a HTTP POST; include @HttpDelete keyword before method name for denoting a method to respond on a HTTP DELETE. Similarly for HTTP PUT and PATCH methods
4.                   Make sure that methods responsible for handling HTTP requests have global access specified and static keyword with them.
5.                   The awesome feature is that you can set return type as primitive type, standard objects or custom objects within your salesforce.com development environment. In this example the list of accounts will be returned to client invoking the service.
6.                   In order to pass parameters to service, you can use RestRequest object in a method. Example
  1. The limitation here is that within a REST apex class you can have only one method with @HttpGet keyword.i.e. one method can respond to HTTP GET requests in this class or URL path. same applies for @HttpPost, @HttpDelete, @HttpPut, @HttpPatch

REST annotations in salesforce:

@httpGet :  it is to return specific resource  or getting some resource in response.
@httpPost : for creating new resource
@httppatch : update specific resource
@httpput : create or update specific resource
@httpDelete : to delete specific resource



      Develop REST SERVICE:
HttpGet method example:
How to call rest service from other org:


REST code for authenticate:
HttpRequest request = new HttpRequest();
  request.setEndpoint('https://test.salesforce.com/services/Soap/u/22.0');
  request.setMethod('POST');
  request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
  request.setHeader('SOAPAction', '""');
  request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>username@gmail.com</username><password>passwordwithToken</password></login></Body></Envelope>');
  Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
    .getChildElement('Body','http://schemas.xmlsoap.org/soap/envelope/')
    .getChildElement('loginResponse','urn:partner.soap.sforce.com')
    .getChildElement('result','urn:partner.soap.sforce.com');
  
  //----------------------------------------------------------------------
  // Grab session id and server url (ie the session)
  //----------------------------------------------------------------------
  String SERVER_URL = resultElmt.getChildElement('serverUrl','urn:partner.soap.sforce.com').getText().split('/services')[0];
  String SESSION_ID = resultElmt.getChildElement('sessionId','urn:partner.soap.sforce.com').getText();

You can get response in XML or JSON way by just keeping “.XML” or “.JSON”
 

Possible errors:
Don’t keep email id in URL header without encrypt like
You will get 404 error and error msg like
"errorCode":"NOT_FOUND","message":"The requested resource does not exist

 HttpPost :
  You keep parameters in post method
Example 1: with simple parameters

Request code like below


Result :
You have specify which type of body you are setting up in header like “application/xml”  or “application/json” . whatever you are passing.
Parameter names should match with xml elements …like …in xml name and email is matched with parameter names of “echotest1” method. Otherwise you will get an error.

Example 2: Rest example with user defined class with example code
Request receiver class code:

Request sender from outside salesforce or other org

You have to define namespace for globally defined objects and finally keep that entire information in string of body for  sent out.
NOTE : you cannot set parameters as list or nested list or map of standard objects or custom object …like  map<object,object> , List<list<contact>> …. Use xml or JSON for overcome this limitation.
Salesforce examples for REST :

No comments:

Post a Comment