Sub topic 12
Designing and versioning your API
This chapter assumes you can write an @RestResource class with @HttpGet and @HttpPost methods. It also assumes you know how to set status codes on RestResponse. Here you design the contract those classes expose, and you plan for changing it without breaking callers.
Treat the URL as a contract
Once an external system calls your endpoint, the URL, the JSON shape and the status codes are a contract. Changing them breaks clients you may not control. A few conventions keep the contract predictable:
- Use plural nouns for resources, such as
/v1/Accounts/*, not verbs such as/v1/getAccount. - Let the HTTP method carry the action: GET reads, POST creates, PUT replaces, PATCH updates part of a record, DELETE removes.
- Use the same field names and casing in every response.
- Use the same error body everywhere.
Put the version in the URL mapping
The standard Salesforce REST API puts the version in the path, as in /services/data/v62.0/. Apex REST has no built-in versioning, so you add it yourself in urlMapping. Each version is a separate class with its own mapping. Two classes cannot share the same urlMapping.
| Change | Breaking? | Action |
|---|---|---|
| Add an optional response field | No | Ship in the current version |
| Add an optional query parameter | No | Ship in the current version |
| Rename or remove a response field | Yes | New version |
| Change a field's type | Yes | New version |
| Make an optional input required | Yes | New version |
| Change a status code for an existing case | Yes | New version |
A v2 with a stable error shape
The v1 class from earlier chapters returns an Account directly and sends an empty body with a 404. Version 2 returns a purpose-built response class, so the JSON no longer changes when the sObject does. It also returns the same error body for every failure.
@RestResource(urlMapping='/v2/Accounts/*')
global with sharing class AccountRestServiceV2 {
global class AccountDto {
global String id;
global String name;
global String industry;
}
global class ErrorDto {
global String code;
global String message;
}
@HttpGet
global static void getAccount() {
String idText = RestContext.request.requestURI.substringAfterLast('/');
Id accountId;
try {
accountId = Id.valueOf(idText);
} catch (StringException e) {
write(400, error('INVALID_ID', 'The path must end with a valid record Id.'));
return;
}
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
write(404, error('NOT_FOUND', 'No Account found for Id ' + accountId));
return;
}
AccountDto dto = new AccountDto();
dto.id = rows[0].Id;
dto.name = rows[0].Name;
dto.industry = rows[0].Industry;
write(200, dto);
}
private static ErrorDto error(String code, String message) {
ErrorDto e = new ErrorDto();
e.code = code;
e.message = message;
return e;
}
private static void write(Integer status, Object body) {
RestResponse res = RestContext.response;
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(body));
}
}The methods return void and write responseBody themselves. This way the success and error paths both go through one helper, and clients can parse every response the same way. The code field is a machine-readable string, so clients can branch on it. They don't have to parse message.
Keep versions maintainable
- Share logic, not endpoints. Move queries and business rules into a service class that both
AccountRestServiceandAccountRestServiceV2call. Each REST class then only maps HTTP to Apex and back. - Test each version separately. A v1 test that still passes shows you did not break old clients.
- Announce deprecation before removal. Tell callers which version is retiring and when. Check your logs for v1 traffic before deleting the class.
- Add to a version, don't change it. New optional fields are safe. Anything else goes in the next version.
Exercise
Your v2 response currently returns industry as a string. A partner asks you to return it as an object with label and value. Do you change v2 in place, and why?
Show answer
No. Changing a field's type breaks existing v2 clients that expect a string. Create /v3/Accounts/* in a new class that returns the object. Keep v2 running until clients have moved, then retire it. Alternatively, add a new optional field such as industryDetail to v2. That is non-breaking, and you leave industry unchanged.