Salesforce Inbound REST API with Param

Salesforce Inbound REST API with Param

Sample Code:

@RestResource(urlMapping='/AccountRESTAPI/*')
global class AccountRESTAPIController {
    
    @HttpGet
    global static Account fetchAccount() {
        
        Account objAccount = new Account();   
        RestRequest req = RestContext.request;
        String accNum = req.params.get( 'accNum' );                                                
        return [ SELECT Id, Name, AccountNumber, Industry FROM Account WHERE AccountNumber =: accNum ];
        
    } 

}

Connected App:

Output:

Workbench:

Postman Client:

Test Class:

@isTest
private class AccountRESTAPIControllerTest {
    
    testMethod static void testAccountAPI() {
        
        Account objAcc = new Account( Name = 'Testing12345', AccountNumber = '12345' );
        insert objAcc;
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/AccountRESTAPI';
        req.addParameter( 'accNum', '12345' );
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response = res;
        Account objFetchedAcc = AccountRESTAPIController.fetchAccount();
        system.assertEquals( '12345', objFetchedAcc.AccountNumber );
        
    }
}

Leave a Reply