Sub topic 1
REST Basics and When to Write an Apex REST Service
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax, classes and static methods.
- SOQL and DML fundamentals.
- HTTP basics: methods, headers, status codes, and request and response bodies.
- JSON structure (objects, arrays, strings, numbers, booleans, null).
- Salesforce profiles and permission sets, at the level of "a user has access to an object or a class because of one of these."
You do not need to have written an Apex REST service before. This chapter gives you the working model and the decision criteria. Later chapters build the service step by step.
What REST means in practice
REST (Representational State Transfer) is a style for designing web APIs. A client sends an HTTP request to a URL. The server returns a representation of a resource, usually JSON. Four ideas matter for this tutorial:
- Resources have URLs. A URL identifies a thing, such as
/v1/Accounts/001XXXXXXXXXXXXXXX. The URL names the thing, and the HTTP method says what to do with it. - HTTP methods carry the intent.
GETreads,POSTcreates,PUTreplaces,PATCHchanges part of a resource, andDELETEremoves it. - Each request is self-contained. The server does not remember earlier requests. Every call carries its own credentials and input.
- Status codes report the outcome.
200and201mean success.400means the client sent bad input.404means the resource is missing.500means the server failed.
A REST API is not a strict standard, and many APIs follow these ideas loosely. What matters for you is that clients can predict how the API behaves.
Methods and their usual meaning
| Method | Typical meaning | Safe (no changes) | Idempotent (repeat gives same result) |
|---|---|---|---|
| GET | Read a resource | Yes | Yes |
| POST | Create a resource or run an action | No | No |
| PUT | Replace a resource | No | Yes |
| PATCH | Partially update a resource | No | Not guaranteed |
| DELETE | Remove a resource | No | Yes |
Idempotency matters for retries. If a client times out on a PUT and sends it again, the result is the same. If it retries a POST that creates a record, it can create a duplicate. You will design for this in the API design chapter.
Where Apex REST fits on the Salesforce platform
Salesforce already exposes data through several APIs. Apex REST is one more option, and you write it yourself.
| Option | What it gives you | You write |
|---|---|---|
| Standard REST API | CRUD on sObjects, SOQL and SOSL queries, describe calls, composite requests | Nothing on the server |
| Composite and sObject Collections resources | Several operations in one call, up to 200 records per collection call | Nothing on the server |
| Apex REST | Your own URLs, input shapes and output shapes backed by Apex | An Apex class |
| Apex SOAP (`webservice` methods) | A SOAP endpoint for clients that require WSDL | An Apex class |
| Flow or platform events | Asynchronous, event-based integration | Configuration |
The standard REST API is generic. It exposes Salesforce's object model as it is. If a client wants an Account, it asks for the Account and gets the fields that Salesforce defines. That is often exactly what you want, and you should start there.
Apex REST is a custom API. You choose the URL, the request body and the response body. The method that handles the request is Apex code that runs on the platform. The client sees your contract, not your data model.
The request path
Salesforce routes an Apex REST call as follows:
Apex REST endpoints live under /services/apexrest/ on your org's domain. A class mapped to /v1/Accounts/* is reachable at https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/....
When to write an Apex REST service
Writing a custom service costs more than using the standard API. You write the code, test it, secure it and keep it stable for every client that depends on it. Write one when the standard API cannot do the job, or when it can only do it badly.
Good reasons
- One call must run several steps atomically. A client needs to create an Account, a Contact and an Opportunity, and either all three are saved or none are. Apex can wrap these in one transaction and roll back on failure. Composite requests can group calls, but the logic stays in the client and the rules are harder to enforce.
- You need business logic on the server. Examples are validation that the platform's validation rules cannot express, calculations, or calls to other services. Keeping the logic in Apex means every client gets the same behavior.
- You want to hide the data model. The client should not need to know that a field is called
Custom_Status__c. Your service can return{"status": "active"}and change the underlying fields later. - You need a different shape. Mobile clients and external systems often want one compact response that joins data from several objects. The standard API would need several round trips.
- You need a custom operation, not a record. Examples are "recalculate the quote", "merge these two accounts" or "check eligibility." These are actions, and the standard API has no endpoint for them.
- You must reduce the number of calls from a slow or metered client. One well-designed call is cheaper than five.
Poor reasons
- The client only needs to read or write records. The standard REST API already does this, with documentation, versioning and tooling. A custom class that copies it adds code to maintain and gains nothing.
- You want to avoid learning the standard API. The cost of learning it is much lower than the cost of owning a custom one.
- You plan to do heavy processing inside the request. A REST call runs synchronously with synchronous governor limits. Long jobs belong in asynchronous Apex, with the REST call only starting the job and returning a status resource.
- The consumer is a Salesforce component. Lightning components can call Apex methods directly, with no REST layer.
A decision checklist
Ask these questions in order:
- Can the standard REST API, with its composite resources, do this in an acceptable number of calls? If yes, use it.
- Does the operation need server-side logic, a single transaction or a custom contract? If no, reconsider whether you need custom code at all.
- Is the caller outside Salesforce, or a Salesforce client that needs plain HTTP? If the caller is a Lightning component, use an
@AuraEnabledmethod instead. - Can the work finish within the synchronous limits? If not, start asynchronous work and return quickly.
If you reach step 4 with "yes" answers throughout, an Apex REST service is a good fit.
What an Apex REST class looks like
You will learn each part in later chapters. A first look at the whole shape helps you see what you are choosing to build.
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return null;
}
return rows[0];
}
}Read it in four parts:
@RestResource(urlMapping='/v1/Accounts/*')turns the class into a resource. The*is a wildcard, so/v1/Accounts/001...matches.globalis required on the class and on its handler methods. Handler methods must also bestatic.@HttpGetmarks the method that answersGETrequests. A class can have at most one method per HTTP method.RestContextgives the method access to the incoming request and the outgoing response. The returnedAccountis serialized to JSON automatically.
with sharing and WITH USER_MODE make the query respect the caller's record access and field permissions. Without them, the code would run in system context and could expose data the caller should not see. This is covered fully in the security chapter, but note now that a custom endpoint is your responsibility to secure.
Calling the service
A client calls your service like any HTTPS endpoint. It sends an OAuth access token in the Authorization header:
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"Replace MyDomainName and the record Id with your own values. The token comes from an OAuth flow, which a later chapter covers. The user the token belongs to must also have access to the Apex class, through a profile or permission set.
Trade-offs to keep in mind
Custom services give you control, and that control has a price.
| Benefit | Cost |
|---|---|
| Contract you design | You must document and version it |
| Server-side logic and transactions | You must write and maintain tests |
| Hidden data model | Changes to your service can break clients |
| Fewer round trips | A single request is bound by synchronous governor limits |
| Custom error handling | You must set status codes and messages yourself |
Two limits shape the design from the start. Apex code in a request shares the synchronous governor limits, such as 100 SOQL queries and 150 DML statements per transaction. Salesforce also caps the size of REST request and response bodies, so very large payloads need paging or an asynchronous design. Later chapters return to both.
Common mistakes at this stage
- Building a custom service when the standard API would work. Check the standard API first.
- Exposing sObjects directly as the contract. If you return an
Account, adding or removing a field on the object changes your API. Consider dedicated response classes for stable contracts. - Forgetting that the service is a public entry point. Anyone with a valid token and class access can call it. Treat all input as untrusted.
- Putting long-running work in the handler. Keep the request fast and push heavy work to a queue.
Exercise
A partner system needs to create an Account and its primary Contact, and must never end up with an Account that has no Contact. Should you use the standard REST API or a custom Apex REST service, and why?
Show answer
A custom Apex REST service is the better fit. Apex can insert both records in one transaction and roll back if the second insert fails, so the partner never sees a half-created pair. The standard API can group calls with a composite request, but the all-or-nothing rule and any business validation would then live in the client. A custom service keeps that rule on the server for every caller.
Exercise
A reporting tool only needs to read Opportunity records by Id and run SOQL queries. Is an Apex REST service justified?
Show answer
No. The standard REST API already provides sObject reads and a query endpoint, with permissions enforced for the caller and a documented, versioned contract. A custom class would duplicate that and add code to test and maintain without adding any capability.
Exercise
Your Lightning web component needs to fetch account data. Should you build an Apex REST service for it?
Show answer
Usually not. A Lightning web component can call an Apex method annotated with @AuraEnabled directly, with no HTTP layer, URL mapping or OAuth setup. Apex REST is meant for callers that use plain HTTP.