Sunday, October 30, 2022

How to use @HttpGet annotation with parameters in URL in salesforce?

 Below is an example of webservice which need id or any unique identifier as a parameter in request and it will return record associated with it.

@RestResource(urlMapping='/getAccountOnExternalIdtofetchsinglerecord/*')

global with sharing class getAccounttoSingleRecord {

      @Httpget

      global static String fettringchAccount(){

      Account obj=new Account();

      RestRequest req = RestContext.request;

      RestResponse res = Restcontext.response;

      string accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

      obj=[Select id , name from Account where id=:accId];

      string serializeResponse=JSON.Serialize(obj);

      return serializeResponse;

      }

   }

  • The above web service will be accessible at below URL with GET method from external system after successful authentication.

'https://instance.salesforce.com/services/apexrest/getAccountOnExternalIdtofetchsinglerecord/' + externalAccId;

Now, what if we want to pass more than one parameter in request URL.

In this case we can use params variable of RestRequest class.

The params returns the parameters that are received by the request.

The return type is of Type: Map<String, String>.

 Below is an example of webservice which need email and phone as a parameter in request and it will return contact record associated with it.

@RestResource(urlMapping='/getContactFromEmailAndPhone/*')

   global with sharing class getContactRecord {

        @Httpget

      global static Contact fetchContact(){

        Contact obj=new Contact();

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        Map<String, String> requestParam = req.params;

        String conEmail=requestParam.get('email');

        String conPhone=requestParam.get('phone');

        obj=[Select id,lastname,email,phone from contact where email=:conEmail and phone=:conPhone];

       /***Modify the HTTP status code that will be returned to external system***/

        res.statuscode=201;

       /***Modify the HTTP status code that will be returned to external system***/

        return obj;

      }

   }

The above webservice will be accessible at,

/services/apexrest/getContactFromEmailAndPhone?email=testemail2@gmail.com&phone=123

Let's try to test the webservice from workbench as shown below and let's see the result.

How to use @HttpGet annotation with parameters in URL in salesforce?

1 comment: