REST Resources in Apex (@RestResource)
By the end of this lesson, you'll be able to:
- Expose an Apex class as a custom REST endpoint using @RestResource
- Handle a GET and a POST request in a REST resource class
- Explain the difference between making a callout and exposing one
Prerequisites: "Named Credentials and External Credentials"
The direction flips
Every earlier lesson in this module was Apex reaching out to an external system. @RestResource does the opposite: it exposes an Apex class as a REST API endpoint that external systems can call into Salesforce — genuinely the reverse integration direction.
Exposing a GET endpoint
@RestResource(urlMapping='/accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
return [SELECT Id, Name, Industry FROM Account WHERE Id = :accountId];
}
}
@RestResource(urlMapping='/accounts/*') names the URL path; @HttpGet marks this specific method as handling GET requests to that path. Note global — REST resource classes and their methods must be global, since they're callable from entirely outside the org, a stricter exposure than even @AuraEnabled's public.
Handling a POST with a request body
@RestResource(urlMapping='/accounts/*')
global with sharing class AccountRestService {
@HttpPost
global static Id createAccount(String name, String industry) {
Account acc = new Account(Name = name, Industry = industry);
insert acc;
return acc.Id;
}
}
@HttpPost handles incoming POST requests — parameters here map automatically from the incoming request's JSON body (Lesson 2's JSON.deserialize concept, handled implicitly by the framework this time) onto the method's own parameters.
Exercise
Write a REST resource ContactRestService at /contacts/* with an @HttpGet method returning all Contacts (Id, LastName).
Show hint
@RestResource(urlMapping='/contacts/*') global with sharing class ...
REST Resources in Apex (@RestResource) Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Everything so far has been Apex calling an external system — this lesson flips the direction: exposing Apex itself as a REST endpoint an external system can call into.