[SalesForce] How to pass parameters in web service class in Salesforce

I am writing a web service that would expose Salesforce fields and this one would be called by an external system.

The scenario is that when a user there would views a record detail page of the external system, then a "field present in there needs to get updated with Salesforce Account OwenerID" for that particular record.

So, when the user clicks the record, the web service needs to get that recordId of the external system (memberId) and query back in Salesforce with the memberID and send the response back in JSON format.

The object that I am working is Account, where in I need to send the Account Name, OwnerID and a Custom Field. And the parameter used in the WHERE condition is the "custom filed".

@RestResource(urlMapping='/GetAccountDetails/*')
global with sharing class GetAccountDetails
{
   @HttpGet
   global static String getManagers(RestRequest req, RestResponse res) {
    String memberID = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
    //Account result = [SELECT Id, Name, Member_c, OwnerID FROM Account WHERE Member__c = :memberID];
    String accountFields = 'SELECT Id, Name, Member_Number__c, OwnerID FROM Account WHERE Member__c';
    String detailsJSON = JSON.serializePretty(Database.query(accountFields));
    system.debug('******'+detailsJSON);
    return detailsJSON;
}
}

And would also like to know how do I invoke this service at the external system, like, by any URL call or any other way.

Best Answer

You don't need to pass the Request/Response into the method. I would have written this like:

@RestResource(urlMapping='/GetAccountDetails/*')
global with sharing class GetAccountDetails
{
  @HttpGet
  global static List<Account> getManagers()
  {
    RestRequest req = RestContext.request;
    String memberID = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
    return [SELECT Id, Name, Member_c, OwnerID FROM Account WHERE Member__c = :memberID];
  }
}

This assumes you are passing an additional String into the parameters.

And would also like to know how do I invoke this service at the external system, like, by any URL call or any other way.

You could use a SOAP service if you want, but IMO REST is usually the better way to go.

EDIT: @sfdcfox also pointed out that returning the native object allows the caller to specify a JSON or XML response.

EDIT 2: String version of the query.

String query = 'SELECT Id, Name, Member_c, OwnerID FROM Account WHERE Member__c = :memberID';
return Database.query(query);
/* you could also cast it to Account before returning
List<Account> result = Database.query(query);
return result;
*/
Related Topic