Building a Custom Apex REST Service
By the end of this lesson, you'll be able to:
- Expose an Apex class as a custom REST endpoint with @RestResource
- Handle GET and POST requests with @HttpGet and @HttpPost
Prerequisites: Parsing JSON Responses
@RestResource and the URL mapping
@RestResource(urlMapping='/Accounts/*') on a global class exposes it at /services/apexrest/Accounts/{id}. The class must be declared global, and its handler methods global static.
@HttpGet, @HttpPost, and RestContext
Each annotated method handles one HTTP verb. RestContext.request and RestContext.response give access to the incoming request (URL, parameters, body) and let you set the outgoing status code.
A GET endpoint returning an Account
@RestResource(urlMapping='/Accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
String accountId = RestContext.request.requestURI.substringAfterLast('/');
return [SELECT Id, Name, Industry FROM Account WHERE Id = :accountId];
}
}
The Id is pulled from the end of the URL — a GET to /services/apexrest/Accounts/001XXXXXXXXXXXX would call this method with that Id.
Exercise
Write a @HttpPost method on a @RestResource class that creates a Contact from the request body and returns its new Id.
Show hint
Deserialize RestContext.request.requestBody.toString() into a Contact, insert it, return contact.Id.
Building a Custom Apex REST Service — Quick Check
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
@RestResource(urlMapping) turns an Apex class into a custom REST endpoint under /services/apexrest/, with @HttpGet, @HttpPost, @HttpPut, and @HttpDelete marking which method handles each HTTP verb.