How do developers design custom REST endpoints in Apex using annotations and custom payload structures?
Answer
Basics: Standard REST maps to objects. Sometimes a caller needs one call that runs business logic across multiple objects, returns a tailored payload, or enforces a custom contract. Apex REST lets you design that endpoint. Callers reach it at /services/apexrest/<urlMapping>, with the namespace in the URL for managed packages.
How it works:
- Create
global with sharing classwith@RestResource(urlMapping='/orders/*'). - Add static methods with HTTP annotations (one method per verb).
- Read the request via
RestContext.request(URI, params, headers, body) or via typed method parameters, which Salesforce deserializes from the JSON body. - Return an object that Salesforce serializes to JSON, or write to
RestContext.response. - The caller authenticates with OAuth; the integration user needs access to the class (profile/permission set).
Advanced / deep dive: Apex REST runs in system context for data access unless you use with sharing and enforce CRUD/FLS (WITH USER_MODE in SOQL, Security.stripInaccessible). Design guidance: version the URL (/v1/orders/*), return meaningful HTTP codes (400, 404, 409, 500) instead of always 200, accept an External ID to be idempotent, validate input, and keep the payload stable. Use wrappers for request and response. Limits are the normal Apex governors for the transaction; the payload size limit is about 6 MB, so verify it for big payloads. Compared with Flow-based "Invocable" or platform events, Apex REST is synchronous: the caller waits. Do not put callouts and DML in arbitrary order; DML before callout throws an exception.
Code / config example: