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
Ryan Raymundo 1Ryan Raymundo 1 

Unable to do SOQL query inside @RestResource?

Hello everyone, Just wanted to ask why my SOQL query is not working inside @RestResource?
List<Account> recordToUpdate = [Select id from Account where id = '001Dn00000PideYIAR' LIMIT 1];

This code inside @RestResource returns false, which means that it can't get any record. 
But if I run the same code inside the Developer Console it returns true. Why is that?User-added image 
Also using Query Editor shows a record
User-added image

Any help would be appreciated. Thanks in advance!



Hii Ryan 
Try Below Expample
The requirement for the challenge is to return Account and its related contacts, which can be achieved using one SOQL query. I am sharing the code for my apex class that successfully passed the challenge.
//Apex Class

global with sharing class AccountManager{
    global static Account getAccount(){
        RestRequest request = RestContext.request;
        String accountId = request.requestURI.substringBetween('Accounts/','/contacts');
        Account objAccount = [SELECT Id,Name,(SELECT Id,Name FROM Contacts) FROM Account WHERE Id = :accountId LIMIT 1];
        return objAccount;

//Test  class
private class AccountManagerTest{
    static testMethod void testMethod1(){
        Account objAccount = new Account(Name = 'test Account');
        insert objAccount;
        Contact objContact = new Contact(LastName = 'test Contact',
                                         AccountId = objAccount.Id);
        insert objContact;
        Id recordId = objAccount.Id;
        RestRequest request = new RestRequest();
        request.requestUri =
            + recordId +'/contacts';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount!= null);
        System.assertEquals('test Account', thisAccount.Name);

While your code did provide the evrything that was required the JSON returned in the case of single SOQL  is different as compared to your JSON.

Please Mark It As Best Answer If It Helps Thank you!
Hope this helps,