Using cURL in apex to retrieve the records in Salesforce


To retrieve records in Salesforce using a curl request in Apex, you would need to make use of Salesforce’s REST API. Assuming you are well aware of HTTP requests, REST Api and cURL; Here’s an example of how you can construct a curl request in Apex to retrieve records:

String baseUrl = ''; // Replace with your Salesforce instance URL
String apiVersion = 'vXX.X'; // Replace with the desired Salesforce API version

String endpoint = baseUrl + '/services/data/' + apiVersion + '/query/?q=';

String query = 'SELECT Id, Name FROM Account LIMIT 10'; // Replace with your desired SOQL query

String url = endpoint + EncodingUtil.urlEncode(query, 'UTF-8');

HttpRequest request = new HttpRequest();
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

Http http = new Http();
HttpResponse response = http.send(request);

if (response.getStatusCode() == 200) {
    String jsonResponse = response.getBody();
    // Process the JSON response
} else {
    // Handle the error response

In this example, we are constructing the API endpoint by appending the Salesforce API version, followed by the query parameter (q) that contains the URL-encoded SOQL query. We then create an HttpRequest object, set the necessary headers (including the authorization header with the access token), and specify the HTTP method as GET.

After sending the request using the Http class, we can check the response status code to determine if the request was successful (status code 200). If successful, we can process the JSON response in the getBody() method. Otherwise, we can handle the error response accordingly.

Please note that this code snippet assumes you are executing it within a context where the user has the necessary permissions to access the records specified in the SOQL query. Additionally, make sure to update the baseUrl and apiVersion variables with the appropriate values for your Salesforce instance.

Want to learn more, Create remote site using Apex.

Please reach out to us if you are looking for an expert who can help you to achieve the integration using cURL: Contact Us