Wednesday, 18 December 2019

Apex WebService in Salesforce example

External system/service can consume data from salesforce through REST services.
Below is an example on how to write an apex webservice with GET method

@RestResource(urlMapping='/GetDetails/*')
global with sharing class GetDetails {
    @HttpGet
    global static ResponseHandler GetInvestorFundDetail()
    {
        ResponseHandler response = new ResponseHandler();
        try
        {
            List<Account> objAccount;
            RestRequest req = RestContext.request;
            string AccountID = req.params.get('AccountID');
            objAccount = [SELECT Id,amount FROM Account WHERE Id =: AccountID]; 
           If(  objAccount.size() > 0)
            {
            response.Status = 'Success';
            response.ErrorCode = '200';  
            response.records = objAccount;
            response.Message = 'Success : Found Contract';
            }
             else
            {
            response.Status = 'Fail';
            response.Message = 'Fail : No Account found';
            response.errorCode = '204';
          }
        }
        catch(Exception Ex)
        {
            system.debug('**** Exception '+ex);
             response.Status = 'error';
            response.Message = 'Exception while retreving Account Fund Details'+ex;
            response.errorCode = '500';
        }
         return response;
    }
    
    global with sharing class ResponseHandler {

    // Declaring all the attributes used to create the Response

    public String status {get; set;}
    public String message {get;set;}
    public String errorCode {get; set;}     
    public List<Account> records {get;set;}     
    public decimal isaLimit {get;set;}
        
     }

}