Wednesday, December 19, 2018

How to Read REST API GET Parameters in Apex

This post explains How we can read the REST API GET parameters in Apex
We can read the parameters based on URL

Example:1

URL: /services/apexrest/getContactdetails?accountId=Accountd&leadSource=Web
Rest Method: GET
Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.params.get('accountId');
        strLeadSource = restReq.params.get('leadSource');
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, Email FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}
above class return the list of contacts based on passing parameters accountId and lead source
Example URL
/services/apexrest/getContactdetails?accountId=0017F00000idCUi&leadSource=Web
Result:

Example: 2

URL: /services/apexrest/getContactdetails/Accountd&Web
Rest Method: GET

Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('/') + 1);
        strAccId = strAccId.left(strAccId.lastIndexOf('&'));
        strLeadSource = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('&') + 1);
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, LeadSource FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}

Example URL:
/services/apexrest/getContactdetails/0017F00000idCUi&Web
Result:



Let Us know if you have any queries.
Happy Learning!!

No comments:

Post a Comment