Sub topic 12
Designing and Versioning Your API
This chapter covers how to design the public surface of a custom Apex REST service so it stays usable as it grows. It assumes you can already write a @RestResource class, map HTTP methods with @HttpGet, @HttpPost and the other annotations, and return status codes. It also assumes you know basic HTTP and JSON. Here the focus moves from "how do I make it work" to "how do I keep it working for callers I don't control".
Why design matters more than code
Once an external system calls your endpoint, the URL, the JSON field names and the status codes become a contract. Changing any of them can break a caller that you can't see and can't redeploy. Apex lets you change the code in seconds, but you can't change the callers.
Good design reduces the number of breaking changes you will ever need. Versioning gives you a way to make the ones that remain.
Model resources, not actions
REST treats URLs as nouns (resources) and HTTP methods as verbs. Apex REST gives you one urlMapping per class, so the URL shape you pick is the main design decision.
| Poor design | Better design | Why |
|---|---|---|
| `POST /v1/createAccount` | `POST /v1/Accounts` | The method already says "create". |
| `GET /v1/getAccountById?id=001...` | `GET /v1/Accounts/001...` | The identifier is part of the resource path. |
| `POST /v1/deleteAccount` | `DELETE /v1/Accounts/001...` | Use the HTTP method that matches the intent. |
| `GET /v1/Accounts/001.../getContacts` | `GET /v1/Accounts/001.../Contacts` | A child collection is a noun. |
Keep these conventions consistent across all of your classes:
- Use plural nouns for collections (
/Accounts), and a path segment for one record (/Accounts/{id}). - Use query parameters to filter, sort and page a collection, not to identify a single record.
- Use the HTTP method to carry the action. Reserve a verb in the URL for operations that really aren't CRUD, such as
POST /v1/Accounts/{id}/merge.
Choosing the right method
Each method has a defined meaning. Callers and intermediaries (proxies, retry libraries) rely on it.
| Method | Meaning | Safe | Idempotent |
|---|---|---|---|
| `GET` | Read | Yes | Yes |
| `POST` | Create, or run a non-idempotent action | No | No |
| `PUT` | Replace a whole record | No | Yes |
| `PATCH` | Change some fields | No | Not guaranteed |
| `DELETE` | Remove | No | Yes |
"Safe" means the call doesn't change data. "Idempotent" means that calling it twice leaves the system in the same state as calling it once. A GET that updates a record breaks the first property. A POST that creates a duplicate on each retry shows why idempotency matters, and the next section deals with it.
Design for retries
Networks fail. A client that times out will often resend the request without knowing whether the first one worked. If your POST inserts a record each time, a retry creates a duplicate.
Two common fixes:
- Upsert on an external ID. Have the client send its own identifier and use
upsertagainst an external ID field. A repeated call updates the same record. - Idempotency key. Accept a client-generated key in a header and check whether you have already processed it.
The first is simpler in Salesforce because it needs no extra storage. This example accepts a PUT keyed by an external ID in the path:
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpPut
global static Account upsertAccount(String name, String industry) {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String externalId = req.requestURI.substringAfterLast('/');
Account acc = new Account(
ExternalKey__c = externalId,
Name = name,
Industry = industry
);
upsert as user acc ExternalKey__c;
res.statusCode = 200;
return acc;
}
}This assumes your org has a custom Account field named ExternalKey__c, marked as External ID and Unique. Sending the same request twice produces one record.
Shape the JSON deliberately
Apex serializes the object you return, so a returned sObject exposes whatever fields were queried. That is convenient, and it is also risky: if you later add a field to the query, it appears in the output without anyone deciding it should.
For a stable contract, return a purpose-built wrapper class instead of an sObject.
global class AccountDto {
global String id;
global String name;
global String industry;
global AccountDto(Account a) {
this.id = a.Id;
this.name = a.Name;
this.industry = a.Industry;
}
}A wrapper gives you four benefits:
- The output has only the fields you chose.
- You can rename a Salesforce field without renaming the JSON property.
- You avoid the
attributesblock that Salesforce adds when it serializes ansObject. - You can reshape data (for example, nest an address) without touching the schema.
Follow some naming rules and keep them everywhere:
- Pick one style for property names, such as
camelCase, and don't mix it withsnake_case. - Don't change a property's type. A number that becomes a string breaks typed clients.
- Use ISO 8601 for dates and datetimes. Apex serializes
Datetimein this format by default. - Return an empty list
[]for "no results" on a collection, notnull.
Standardize errors
A consistent error body lets clients write one error handler. Define a single shape and use it in every method.
global class ApiError {
global String code;
global String message;
global ApiError(String code, String message) {
this.code = code;
this.message = message;
}
}Use machine-readable code values such as NOT_FOUND or VALIDATION_FAILED. Clients can branch on a code, while message is for people and may change wording. Don't put stack traces or internal field names in message.
Apex REST lets you set the response body yourself. For a custom error body, write it to RestResponse:
private static void writeError(Integer status, String code, String message) {
RestResponse res = RestContext.response;
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(new ApiError(code, message)));
}When you write responseBody yourself, make the method return void. If the method returns a value, Apex serializes the return value and overwrites the body you set.
Collections: filtering and paging
An endpoint that returns "all accounts" will eventually hit heap or query limits. Design collection endpoints with a limit from the first version.
@HttpGet
global static List<AccountDto> listAccounts() {
RestRequest req = RestContext.request;
Integer pageSize = 50;
String sizeParam = req.params.get('pageSize');
if (String.isNotBlank(sizeParam) && sizeParam.isNumeric()) {
pageSize = Math.min(Integer.valueOf(sizeParam), 200);
}
Integer offset = 0;
String offsetParam = req.params.get('offset');
if (String.isNotBlank(offsetParam) && offsetParam.isNumeric()) {
offset = Integer.valueOf(offsetParam);
}
List<AccountDto> out = new List<AccountDto>();
for (Account a : [
SELECT Id, Name, Industry
FROM Account
WITH USER_MODE
ORDER BY Name, Id
LIMIT :pageSize
OFFSET :offset
]) {
out.add(new AccountDto(a));
}
return out;
}Points to note:
- The server caps
pageSizeat 200, whatever the client asks for. Never trust the client to protect your limits. ORDER BYwith a unique tiebreaker (Id) keeps pages stable. Without a deterministic order, records can repeat or disappear between pages.- SOQL
OFFSEThas a maximum of 2,000. For large data sets, page with a keyset instead: sort byIdand ask for records whereIdis greater than the last one the client saw.
Versioning
You can change a service in two ways: compatible changes and breaking changes.
| Compatible (no new version) | Breaking (needs a new version) |
|---|---|
| Add an optional input parameter | Remove or rename a parameter or JSON property |
| Add a new JSON property to a response | Change a property's type or meaning |
| Add a new endpoint | Make an optional input required |
| Add a new status code for a new situation | Change the status code of an existing situation |
Callers should ignore unknown JSON properties, so adding fields is normally safe. Tell your clients about that rule in your documentation.
Version in the URL
Apex REST has no built-in versioning feature. The usual approach is to put the version in the urlMapping, as the examples in this tutorial do with /v1/. You publish a second class for the new version and keep the old one running.
@RestResource(urlMapping='/v2/Accounts/*')
global with sharing class AccountRestServiceV2 {
// v2 contract: breaking changes live here
}The two classes live side by side, and each has its own tests. You can share logic through a normal service class that both call, so the version classes stay thin.
Use this layering rule: the REST class parses input, calls the service, and shapes output. Business rules belong in the service class. When v2 needs a different JSON shape, you add a new wrapper class and leave the v1 wrapper alone.
Other versioning options
| Approach | Example | Trade-off |
|---|---|---|
| URL path | `/v2/Accounts` | Clear and easy to test with curl. Needs a new class per version. |
| Header | `Accept-Version: 2` | Clean URLs. Harder to see and test, and you must read the header yourself. |
| Query parameter | `/Accounts?version=2` | Easy to add. Easy to forget, and mixes routing with filtering. |
For Apex REST, URL path versioning fits best because the platform routes by urlMapping. The other two options require one class to branch on a value, which makes that class harder to read and test.
Retiring an old version
Removing a version is a breaking change too, so plan it.
- Announce the end date to known callers well before it.
- Add a
DeprecationorSunsetresponse header on the old version so callers can detect it. - Log calls to the old version, using the user name and the user agent, so you know who is still calling.
- Remove the class only after the logs show no traffic.
RestContext.response.addHeader('Sunset', 'Sat, 31 Oct 2027 23:59:59 GMT');Decision checklist
Before you publish an endpoint, check each item:
- The URL is a noun, and the HTTP method states the action.
- Retries are safe, either through an external ID or a key.
- Responses use a wrapper class, not a raw
sObject. - Errors use one shape with a stable
code. - Collection endpoints cap and page their results.
- The URL contains a version.
- Each method has a test that covers success and failure.
Common mistakes
- Returning
sObjectdirectly from a stable endpoint. A later query change alters the contract. - Using
GETfor actions with side effects. Prefetching tools and retries can trigger them. - Returning
200with an error in the body. Clients that check the status code will treat it as a success. - Unbounded collections. A list that works with 100 records fails with 100,000.
- Changing a response in place. Even a "small" rename needs a new version.
Exercise
Your v1 endpoint GET /v1/Accounts/{id} returns a property industry. A new requirement says the property must be renamed sector and become an object with code and label. Which approach is correct, and why? Name one other change that would have been safe to make in v1.
Show answer
Create a /v2/Accounts/* resource class with a new wrapper that has sector, and keep v1 unchanged. Renaming a property and changing its type are breaking changes, so existing callers would fail if v1 changed in place. Both classes can call the same service class. A safe change in v1 would be adding a new optional property, such as website, because clients are expected to ignore unknown properties.
Exercise
A client times out on POST /v1/Accounts and sends the request again. Now there are two identical accounts. Describe a change that makes the retry safe, and name the HTTP method and Apex DML statement you would use.
Show answer
Use PUT /v1/Accounts/{externalKey} and an upsert on an External ID field, for example upsert as user acc ExternalKey__c;. The client supplies the key, so a repeated request updates the same record instead of inserting another. PUT is idempotent, which matches this behavior.