Apex REST Basic Code Sample
This sample shows how to implement a simple REST API in Apex with three HTTP request methods to delete, retrieve, and update a record.
For more information about authenticating with cURL, see the Quick Start section of the REST API Developer Guide.
-
Create an Apex class in your instance from Setup. Enter
Apex Classesin theQuick Findbox, select Apex Classes, and then click New. Add this code to the new Apex class: -
To call the
doGetmethod from a client, open a command-line window and execute the followingcURLcommand to retrieve an account by ID:curl -H "Authorization: BearersessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"- Replace sessionId with the
<sessionId>element that you noted in the login response. - Replace instance with your
<serverUrl>element. - Replace accountId with the ID of an account which exists in your organization.
After calling the
doGetmethod, Salesforce returns a JSON response with data such as the following, where accountId is a placeholder value:
The
cURLexamples in this section don’t use a namespaced Apex class so you don’t see the namespace in the URL. - Replace sessionId with the
-
Create a file called
account.txtto contain the data for the account you will create in the next step. -
Using a command-line window, execute the following
cURLcommand to create a new account, wheresessionIdandinstanceare placeholder values:curl -H "Authorization: BearersessionId" -H "Content-Type: application/json" -d @account.txt "https://instance.salesforce.com/services/apexrest/Account/"After calling the
doPostmethod, Salesforce returns a response with data such as the following, where accountId is the ID of the account you just created with the POST request: -
Using a command-line window, execute the following
cURLcommand to delete an account by specifying the ID, wheresessionId,instance, andaccountIdare placeholder values:curl —X DELETE —H "Authorization: BearersessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"