Newer Version Available

This content describes an older version of this product. View Latest

Apex REST Basic Code Sample

This sample shows you how to implement a simple REST API in Apex that handles three different HTTP request methods. For more information about authenticating with cURL, see the Quick Start section of the Force.com REST API Developer Guide.
  1. Create an Apex class in your instance from Setup by entering New in the Quick Find box, then selecting New and add this code to your new class:
  2. To call the doGet method from a client, open a command-line window and execute the following cURL command to retrieve an account by ID:
    curl -H "Authorization: Bearer sessionId" "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 doGet method, Salesforce returns a JSON response with data such as the following:

    The cURL examples in this section don't use a namespaced Apex class so you won't see the namespace in the URL.

    Note

  3. Create a file called account.txt to contain the data for the account you will create in the next step.
  4. Using a command-line window, execute the following cURL command to create a new account:

    curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d @account.txt "https://instance.salesforce.com/services/apexrest/Account/"

    After calling the doPost method, Salesforce returns a response with data such as the following:

    The accountId is the ID of the account you just created with the POST request.

  5. Using a command-line window, execute the following cURL command to delete an account by specifying the ID:

    curl —X DELETE —H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"