Examples
Apex REST Service
Building a REST Service
Apex REST service exposes Account data with @RestResource.
Introduction to Apex REST Service
Apex REST service is a powerful feature in Salesforce that allows developers to expose Salesforce data and functionality via RESTful web services. The @RestResource annotation is used to define a class as a RESTful service, allowing external applications to access Salesforce data. In this example, we will focus on exposing Account data.
Setting Up Your Apex REST Class
To create an Apex REST service, you'll need to define an Apex class and annotate it with @RestResource. Each method within this class that you want to expose should be marked with @HttpGet, @HttpPost, @HttpPut, or @HttpDelete, depending on the operation you wish to support.
Understanding the Code
In the code example above, we define an Apex class AccountRestResource
that is mapped to the URL pattern /AccountAPI/*
. The doGet
method is marked with @HttpGet, indicating that it handles HTTP GET requests. This method extracts the Account ID from the URL, queries the Account object for the corresponding record, and returns it. The RestRequest
and RestResponse
classes are used to handle the incoming request and outgoing response.
Testing Your REST Service
Once your REST service is deployed, you can test it using tools such as Postman or cURL. For example, to retrieve an Account with a specific ID, send a GET request to the URL:
https://yourInstance.salesforce.com/services/apexrest/AccountAPI/yourAccountId
Replace yourInstance.salesforce.com
with your Salesforce instance URL and yourAccountId
with the ID of the Account you wish to retrieve.
Security Considerations
When developing REST services in Salesforce, it's crucial to consider security. Use the with sharing keyword to ensure that the service respects the running user's sharing rules. Additionally, implement proper authentication mechanisms, such as OAuth, to secure access to your service.
Examples
- Previous
- Batch Job
- Next
- Visualforce Page