Sub topic 3
Enforcing Security and Operating Apex REST Services
Assume you know basic Apex, SOQL, DML, HTTP, JSON, and Salesforce permission sets. This chapter connects service security with testing, deployment, API design, and governor limits.
Enforcing sharing, CRUD, and field-level security
Declare a REST class with sharing so queries respect the caller's record-sharing rules. Sharing alone does not enforce object permissions or field-level security (FLS). Use user-mode operations for both:
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class SecureAccountService {
@HttpGet
global static Account getAccount() {
String idValue = RestContext.request.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :idValue
WITH USER_MODE
LIMIT 1
];
return rows.isEmpty() ? null : rows[0];
}
@HttpPost
global static Account createAccount(String name) {
Account account = new Account(Name = name);
insert as user account;
return account;
}
}WITH USER_MODE checks object and field permissions during the query. insert as user checks permissions during DML. If you need graceful handling for inaccessible fields, use Security.stripInaccessible and return a deliberate error response. Do not use without sharing unless you have documented, reviewed reasons.
Writing tests for REST handlers
Apex tests can call the handler directly. Build RestRequest and RestResponse, assign them to RestContext, and assert both the returned data and status code. Use System.runAs with a suitable test user when sharing or permissions affect behavior.
@IsTest
private class SecureAccountServiceTest {
@IsTest
static void returnsVisibleAccount() {
Account account = new Account(Name = 'Test Account');
insert account;
RestRequest request = new RestRequest();
request.requestURI = '/services/apexrest/v1/Accounts/' + account.Id;
request.httpMethod = 'GET';
RestContext.request = request;
RestContext.response = new RestResponse();
Account result = SecureAccountService.getAccount();
Assert.areEqual(account.Id, result.Id);
}
}Calling the service and debugging it
After deployment, callers need OAuth authentication and permission to access the Apex class. A 401 usually means the token is missing or expired. A 403 often means the user lacks class or object access. A 404 can mean the URL mapping or record is wrong.
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"Use debug logs for the authenticated user. Avoid logging access tokens or sensitive request bodies.
Designing and versioning your API
Keep resource names and response shapes stable. Put a version in the URL, such as /v1/Accounts. Add /v2 for breaking changes. Prefer additive changes, documented status codes, and consistent error bodies.
Governor limits and bulk-friendly endpoints
Salesforce governor limits restrict database queries, DML statements, CPU time, and response size. Query once instead of querying inside a loop. For imports, accept a list of records and use one bulk DML operation. Validate input before performing database work.
Exercise
What protection does with sharing provide, and what must you add for CRUD and FLS?
Show answer
It enforces record-sharing rules. Use user-mode SOQL and DML, or explicitly enforce permissions with supported security APIs.