REST Services & Serialization in Apex
What Are REST Services in Salesforce?
Short Description
REST services allow external systems (mobile apps, websites, other servers) to call Salesforce APIs and exchange data using HTTP and JSON.
Simple Explanation
REST services turn Salesforce into a data provider, like a waiter serving data when asked.
Gist (Quick Revision)
REST services expose Salesforce data to the outside world using APIs.
1. @RestResource
What Is @RestResource?
@RestResource is an annotation used to expose Apex classes as REST APIs.
Real-Life Example
A mobile app requests customer details from Salesforce.
Basic REST Service Example
@RestResource(urlMapping='/accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
Key Points to Remember
-
@RestResource→ exposes API -
@HttpGet,@HttpPost,@HttpPut,@HttpDelete→ HTTP methods -
Must be
global
Gist (Quick Revision)
@RestResource turns Apex into a REST API endpoint.
2. JSON Serialization & Deserialization
What Is Serialization?
Serialization converts Apex objects into JSON.
Simple Explanation
Serialization is like packing data into a box for transport.
Serialization Example
Account acc = new Account(Name = 'ABC Ltd'); String jsonData = JSON.serialize(acc);
What Is Deserialization?
Deserialization converts JSON back into Apex objects.
Simple Explanation
Unpacking the box and using the data again.
Deserialization Example
String jsonInput = '{"Name":"ABC Ltd"}';
Account acc = (Account) JSON.deserialize(jsonInput, Account.class);
Why This Matters
-
APIs communicate using JSON
-
Required for integrations and REST services
Gist (Quick Revision)
Serialization packs data into JSON; deserialization unpacks it.
3. Handling Large Payloads
What Is a Large Payload?
A large payload is a large JSON request or response that may:
-
Consume high memory
-
Exceed heap size limits
-
Slow performance
Real-Life Example
Sending thousands of records in one API call.
Best Practices for Large Payloads
1. Limit Fields
SELECT Id, Name FROM Account
2. Use Pagination
Return data in chunks, not all at once.
3. Use Streaming (When Possible)
Avoid loading entire JSON into memory.
4. Async Processing
Use Queueable or Batch Apex for large requests.
Gist (Quick Revision)
Large payloads must be handled carefully to avoid heap and performance issues.
