[SalesForce] Execute SOQL query via REST API in apex

I'm trying to execute an SOQL query via REST API call because I want to retrieve custom labels (ExternalString) previous to a date and by Category.

I generate my query like this

Datetime limitDate = Datetime.now();
String query = 'SELECT Name FROM ExternalString WHERE Category = \'Test\' AND LastModifiedDate >= ' + limitDate;

And I'm trying this request

endpoint = '/services/data/v' + apiversion + '/query/q=' + EncodingUtil.urlEncode(query.replace(' ','+'), 'UTF-8');
HttpResponse result;
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(endpoint);
result = http.send(req);

But it's always giving me the following error:

no protocol: /services/data/v48.0/query/q=SELECT%2BName%2BFROM%2BExternalString%2BWHERE%2BCategory%2B%3D%2B%27App%2BM%C3%B3vil%27%2BAND%2BLastModifiedDate%2B%3E%3D%2B2021-03-09%2B23%3A00%3A00

Is there something I'm doing wrong or missing when trying to achieve this functionality?

Thanks in advance!

Best Answer

There's a couple things that need fixing

  1. You need to use ?q= in your query. See the example below from the REST API developer guide
https://yourInstance.salesforce.com/services/data/v51.0/query/?q=SELECT+name+from+Account
  1. The object you're querying is only available through the Tooling API as well so you need to use that endpoint
/services/data/v50.0/tooling/query/?q=
  1. The date value you're using in your filter needs to be in the following format 2021-03-09T00:00:00z
https://yourInstance.salesforce.com/services/data/v48.0/tooling/query/?q=SELECT+Name+FROM+ExternalString+WHERE+Category+=+'App+Móvil'+AND+LastModifiedDate+>=2021-03-09T23:00:00z
  1. You need to pass a session Id in the Authorization header. See REST Headers or look at @sfdcfox's tip for using PageReference to avoid needing this snippet
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept', 'application/json');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());