function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JackHaymesJackHaymes 

How can I use a REST API to query (SELECT Name FROM Accounts) a database?

Amit Chaudhary 8Amit Chaudhary 8
Please try below code.
@RestResource(urlMapping='/myrest2/*')
global with sharing class Rest_Class2
{
   //method will take ID from URL and display the details

   @HTTPGet
   global static Account[] doGet()
   {
        Account[] acts = new Account[]{};
        acts=[select name,type,industry,phone  from Account];
        return acts;
   }
}

Test class.
@isTest
public class Rest_Class2Test
{
  static testMethod void testMethodForAll()
  {
  
    Account testAccount = new Account();
    testAccount.Name='Test Account' ;
    testAccount.Industry='Bank';
    insert testAccount;
      
       Test.startTest();

            RestResponse res = new RestResponse();
            RestRequest req = new RestRequest(); 

            req.httpMethod = 'Get';
            req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated 
            req.requestURI = '/services/apexrest/myrest2/all' ;  
            RestContext.request = req;
            RestContext.response = res;

            List<Account> lstAcc = Rest_Class2.doGet();
            System.assertEquals(lstAcc.size() ,1);
       Test.stopTest();   
  }

  
}

Let us know if this will help you

Thanks
Amit Chaudhary
 
Temoc MunozTemoc Munoz
Hi Jack.

If you want to access the REST API in Salesforce from an external system, please follow this link: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/

If you want to let other systems access Salesforce, please check the code provided by Amit.

If you just want to see how this works in Salesforce, you can access the workbenc for your org: https://workbench.developerforce.com/login.php