Thursday 9 January 2020

Create A rest web service class to expose services

Now we will see how the account management system will expose its services .

Create A rest Web service Class to expose our data :
     Rest web service class structure will be like bellow.
@RestResource(urlMapping='/accountservices/*')
global class AccountServices {
    @HttpGet //read services
    global static void readAccountDetails(){
       
    }
    @HttpPost //write services
    global static void postAccountDetails(){
       
    }
    @HttpPut //read/write services
    global static void putAccountdeyails(){
       
    }
    @HttpDelete //delete services
    global static void deleteAccount(){
       
    }
}
Different possibilities of rest service methods (Click on image)



We are going to work on work bench to test the webservice, it works as service requester (Lead management). It will be used by developers to test the request . Go to workbench (https://workbench.developerforce.com/), utilities , REST explorer . Replace the API like bellow
/service/apexrest/ will be the common , we will ad service name to it to make it as api.

We received the error , since it was case sensitive.  We will change url from Accountservices to accountservices. Then execute. 


Now we got raw resonce . till now we didn’t write any code. Now we will see how to pass parameters .

Enter the parameter parm1=fisrtparam and execute

Even though we have not define any variable with the name pram1, we didn’t receive any error .
Now lets go back to our service class to see how to receive the request . Add the bellow  to your get method to see the request , and execute from work bench again 
RestRequest request  = RestContext.request;
        system.debug('@@@request'+request);
        system.debug('@@@request'+request.params.get('parm1'));
        system.debug('@@@request'+request.requestURI);
Debug: 
open debug log and see . 
We will see what will happen if we return the response . Modify the code like bellow
@HttpGet //read services
    global static string readAccountDetails(){
        RestRequest request  = RestContext.request;
        system.debug('@@@request'+request);
        system.debug('@@@request'+request.params.get('parm1'));
        system.debug('@@@request'+request.requestURI);
        return  request.params.get('parm1');
    }

We will execute the Api from work bench again to see response .


We will se how we can get response  with out return statement .
 Replace the code like bellow
@HttpGet //read services
    global static void readAccountDetails(){
        RestRequest request  = RestContext.request;
        system.debug('@@@request'+request);
        system.debug('@@@request'+request.params.get('parm1'));
        system.debug('@@@request'+request.requestURI);
        RestResponse response  = RestContext.response;
        response.statusCode=200;
        string bodyastring='{message:'+request.params.get('parm1')+'}';
        response.responseBody=blob.valueOf(bodyastring);
    }
And execute the api from work bench
We can see that the parameter we passed was return to us
we don’t need to have  return method for webservices , its good to send response by using the RestResponse.
Now we will see how to use post method .
Response body is must for post method .
We will add debug to post method
RestRequest request  = RestContext.request;
        system.debug('@@@request'+request);
        system.debug('@@@requestParam1'+request.params.get('parm1'));
        system.debug('@@@requestUri'+request.requestURI);
        system.debug('@@@requestBody'+request.requestBody);


see the debug 

Modify the post method so that It can create account from request .
RestRequest request  = RestContext.request;
        system.debug('@@@request'+request);
        system.debug('@@@requestParam1'+request.params.get('parm1'));
        system.debug('@@@requestUri'+request.requestURI);
        system.debug('@@@requestBody'+request.requestBody);
        system.debug('@@@requestBodyAsString'+request.requestBody.tostring());
        map<string,object> requestData=(map<string,object>)(JSON.deserializeUntyped(request.requestBody.tostring()));
        system.debug('@@@requestData'+requestData);
        account acc= new account();
        acc.name=string.valueof(requestData.get('Name'));
        acc.phone=string.valueof(requestData.get('Phone'));
        acc.leadmanagementid__c= string.valueOf(requestData.get('Id'));
        insert acc;
        RestResponse response  = RestContext.response;
        response.statusCode=200;
        response.responseBody=blob.valueOf(JSON.serialize(acc));



enter the request like bellow and see the response 


Now the work is done from Account management side,  we will see how the work will be done from Lead management side .  This work can  be started parallelly  from both Applications. They will decide first the format of JSON data.  Before we go to lead management system Account management system need to create connected App. 
Go to App – scroll down – create new connected App. Give the call back url as https://login.salesforce.com/services/oauth2/callback
You will get consumer key and consumer secret , these are client Id and client secret.    Provide these details with Lead management. along with the username, password,  security token of the user that was linked to the connected



Now we will see the development from lead management system :
1.      We need to establish the connection with account management
2.      We need to send the request
3.      We need to receive the response and process it.

Establishing connection with account management :
Login or create a different salesforce org for lead management. 
Create the remote site settings in lead management , it need to have the url of Account management. this is to add trusted networks .  if we don't add  remote site settings , we will get error unauthorized end point .  To create remorte site settings search remote in quick search box follow UI. 
Create a class with the name AuthCallout , copy the code like bellow
public class AuthCallout {

   public static string basicAuthCallout(){
      String username ='usernameofurOrg@gmail.com';
   
      String password='passwordsecurityToken';
     
 
       string clientId='3MVG9YDQS5WtC11qahskjhdiurriehtuhyrgeygtyC8cjxxxxxxxxxx';
       String ClientSecreet='057372634675655BA4E9D86F25EDxxxxxxxxxxxxxxxxxxxxx'; // if u dont give bad rereuwest in token
      // string redirectURi='https://trainingbatch01-dev-ed.lightning.force.com/';// if u dont give u will get error redirect mismatch in authorise
       String endPointUrl='https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id='+clientId+'&client_secret='+ClientSecreet+'&username='+username+'&password='+password;
       system.debug('@@@endPointUrl'+endPointUrl);
                  //Authorization—https://login.salesforce.com/services/oauth2/authorize
     //Token—https://login.salesforce.com/services/oauth2/token
     //Revoke—https://login.salesforce.com/services/oauth2/revoke (see Revoke OAuth Tokens for details on revoking access)
    
     HttpRequest req = new HttpRequest();
     req.setEndpoint(endPointUrl);
     req.setMethod('POST');
     Http http = new Http();
     HTTPResponse res = http.send(req);
     Map<string,object> obj=(Map<String,object>)JSON.deserializeUntyped(res.getBody());
     system.debug('tokenObj---'+obj);
     system.debug('@@obj--'+obj.get('access_token'));
     System.debug('res@@'+res.getBody());
      
       return String.valueof(obj.get('access_token'));
      
      
   }
}
Main key words to remember
HttpRequest ( to whom we need to ask what we need ask)
HTTPResponse (what we will get back)
Http (protocol) used to send
We will create method to send account details  to AM system.
public class SendAccoountToLM {
    public static void sendAccounttoLM(string  reqAsJosnString){
      // string strSessionid = loginsalesforce.login();
      Account Acc=(Account)JSON.deserialize(reqAsJosnString, Account.class);
        string strSessionid = AuthCallout.basicAuthCallout();// accesstoken it will be valid for only 15 mints
         system.debug('@@@strSessionid'+strSessionid);
        // create a response
        HttpRequest req = new HttpRequest();
        // end point url to whoom we need to request
        String strEndpointURL = 'https://codingbrand-dev-ed.my.salesforce.com/services/apexrest/accountservices';
        req.setEndpoint(strEndpointURL);
        requestWrapper reqBody= new requestWrapper();
        reqBody.Id =Acc.id;
        reqBody.Name=Acc.name;
        reqBody.Phone=Acc.phone;
        req.setBody(JSON.serialize(reqBody));
        // what we need to ask
        req.setMethod('POST');
// to send key
       req.setTimeout(60000);
        req.setHeader('Authorization','Bearer '+strSessionid );
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');
        // ask - invoke - start the action
        HttpResponse res =  new Http().send(req);
        system.debug('@@response'+ res);
        system.debug('@@response'+ res.getBody());
    }
    public class requestWrapper{
      public string Id;
      public string Name;
      public string Phone;
    }
    @future(callout=true)
    public static void futureMethodTosendToAM(string str){
        sendAccounttoLM(str) ;
    }
}
We will write a trigger to invoke this class , as soon as account created . We are going to create a after insert  trigger on account object . we will just invoke the method
Initially we will invoke the method without the help  of future method .
trigger accountAfterInsert on Account (After insert) {
 SendAccoountToLM.sendAccounttoLM(JSON.serialize(trigger.new[0])) ; 
//SendAccoountToLM.futureMethodTosendToAM(JSON.serialize(trigger.new[0]));
   
}
We got the error like bellow since callouts are not supported in triggers

So we have to use future method to call a webservice class from triggers.
trigger accountAfterInsert on Account (After insert) {
 //SendAccoountToLM.sendAccounttoLM(JSON.serialize(trigger.new[0])) ; 
SendAccoountToLM.futureMethodTosendToAM(JSON.serialize(trigger.new[0]));
    }
Now we will save the same record and see.
Now record  is created, see the debug 
It has the new created account details in AM system. Now copy the Id or search with phone number to see if the account is created or not .

Now we have covered both inbound and out bound scenarios of  rest web services . before Going to interview / start work we need to remember the bellow points .
Inbound system / to expose our data we need to provide authentication details , API to the requester . it will have the code with @ @RestResource(urlMapping='/accountservices/*')@HttpGet,@HttpPost,@HttpPut,@HttpDelete.
Outbound call / to get or put data from other system , we need to have the credentials given by them , we create a create request ,   HttpRequest req = new HttpRequest(); req.setEndpoint(strEndpointURL);  req.setHeader('Authorization','Bearer '+strSessionid );
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');        HttpResponse res =  new Http().send(req);



All the Best, only keep the last lines in mind.  Process is always important than remembering syntax. 

    1. REST API has no has no official standard at all because it is an architectural style. SOAP API, on the other hand, has an official standard because it is a protocol.
    2. REST APIs uses multiple standards like HTTP, JSON, URL, and XML while SOAP APIs is largely based on HTTP and XML.
    3. As REST API deploys multiple standards, so it takes fewer resources and bandwidth as compared to SOAP that uses XML for the creation of Payload and results in the large sized file.
    4. The ways both APIs exposes the business logics are also different. REST API takes advantage of URL exposure like @path("/accountservices") while SOAP API use of services interfaces like @WebService.
    5. SOAP API defines too many standards, and its implementer implements the things in a standard way only. In the case of miscommunication from service, the result will be the error. REST API, on the other hand, don't make emphasis on too many standards and results in corrupt API in the end.
    6. REST API uses Web Application Description Language, and SOAP API used Web Services Description language for describing the functionalities being offered by web services.
    7. REST APIs are more convenient with JavaScript and can be implemented easily as well. SOAP APIs are also convenient with JavaScript but don't support for greater implementation.

4 comments:

  1. DO YOU NEED A LOAN? patialalegitimate515@gmail.com We give out loans with an affordable interest rate of 2% Captain One provide Excellent and Professional Financial Services and we are known and genuine money lenders across the globe Our services include the following:
    *Student Loans
    Truck Loan
    Personal Loan
    Debt consolidation loan
    Car Loans
    Business Loan
    Student Loan
    Mortgage Loan
    Refinancing Loan
    Home Loan
    Improvement loan
    Construction Loan
    Looking forward to receive your reply and I will advise you on how to get the fund to your bank account and interest rate will also be discuss before both parties will sign the Loan Contract Agreement.contact us no matter your location no collateral for more information on how to get started: (Whats App) number: +919394133968 patialalegitimate515@gmail.com Mr Jeffery

    ReplyDelete
  2. Loans and Financial Assistance Offer.Apply now! Are you seriously interested in getting a genuine Loan without stress? Do you need this Loan for business and to clear your bills? Then send us an email now for more details via: 2% interest rate.(WhatsApp) number +917310847059 sumitihomelend@gmail.com Mr. Sumiti

    ReplyDelete
  3. THE ONLY LEGITIMATE CRYPTO RECOVERY EXPERT

    I have a strong interest in this subject due to my prior experiences, which have increased my understanding of it. Had I had this information earlier, I would not have fallen victim to scams to the extent that I did, In my quest to earn enough money to retire early, I lost a lot of money to several investing platforms. I was clueless about how to restart after losing everything. Fortunately, I was directed to Morris Gray A Legitimate DIGITAL ASSETS RECOVERY AGENT by a friend. I was able to contact Him on: MORRIS GRAY 830 @ GMAIL COM, and they helped me recover my lost 13.6 BTC and introduced me to

    ReplyDelete
  4. lost 13.6 BTC and introduced me to reliable investment platforms that are currently helping me realize my ambition of retiring early. Given how crucial this is, I hope it will assist someone who is in need of such services, you can reach out to him on, WhatsApp: + 1 607 698 0239 & Email: @ MorrisGray830 @ Gmail, Com...

    ReplyDelete