Custom Rest Resource in Apex
To write REST in Apex, we have to utilize some annotations which access the REST API in your Apex Class – @RestResource(urlMapping=’/version/ApexClassName/’).
This method is called when the HTTP – DELETE is sent which enables the Apex method to be exposed as a REST resource. Then, it deletes the specified resource.
Syntax: @httpDelete
Example:
Write the “RestApi_Delete_Record.apxc” Apex class that involves the “REST DELETE” method to delete a record from the Salesforce case object.
- Create a Delete_Method with no parameters.
- Get the Salesforce ID param that we will pass in Workbench URI.
- Create the case object and query the records using SOQL.
- Use the Delete DML to delete the specified record from the Salesforce case object.
global class RestApi_Delete_Record{
// REST API - Delete
@httpDelete
global static String Delete_Method(){
// Create case object
Case case_obj = new Case();
Map<String,String> id_param = RestContext.request.params;
String caseid=id_param.get('input_id');
case_obj = [select CaseNumber,Status,Priority,Subject from Case where Id =:caseid];
// Delete DML
delete case_obj;
return 'Case Record is Deleted!';}
}
URI and Result:
Go to Workbench and navigate to the REST Explorer. Specify the following URI and execute it by selecting the DELETE HTTP method. Let’s delete the 5002t00000PdzqtAAB case.
Try to open the record in Salesforce (navigate to the case object from the App Launcher). It is deleted and you will find this record in the Salesforce Recycle Bin.
Delete the Record Directly from URI
Let’s delete the following case record which is 5002t00000Pdzr7AAB by specifying this ID in the URI. The URI should be like this: /services/data/v56.0/sobjects/Your_object_APIName/ID.
Navigate to the REST Explorer under the utilities tab and specify the following URI by choosing DELETE as the HTTP method.
We can see that this record is deleted and stored in the Recycle Bin.
Delete Multiple Records Directly from URI
It is possible to delete multiple records at a time from Salesforce by passing the Salesforce record ID to the ids parameter. Each ID is separated by a comma delimiter. The URI looks like this:
Let’s delete two case records (5002t00000PRQ9pAAH, 5002t00000PRqyjAAD) by navigating to the REST Explorer under the utilities tab and specify the following URI by choosing DELETE as the HTTP method.
We can see that these two records are deleted. Let’s check it in the Recycle Bin.
Conclusion
We learned how to delete the Salesforce records using the Workbench HTTP DELETE method with the custom REST API and delete the Salesforce records directly by passing the objects in the URI. All the deleted records are stored in the Salesforce recycle bin. Make sure that you include the @httpDelete annotation in the Apex class.