# How do developers design custom REST endpoints in Apex using annotations and custom payload structures?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Apex REST, Custom Endpoints

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Create `global with sharing class` with `@RestResource(urlMapping='/orders/*')`.
2. Add static methods with HTTP annotations (one method per verb).
3. Read the request via `RestContext.request` (URI, params, headers, body) or via typed method parameters, which Salesforce deserializes from the JSON body.
4. Return an object that Salesforce serializes to JSON, or write to `RestContext.response`.
5. 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:**
```apex
@RestResource(urlMapping='/v1/orders/*')
global with sharing class OrderApi {
    global class OrderReq { public String extId; public String status; }

    @HttpPost
    global static void upsertOrder(OrderReq req) {
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        if (req == null || String.isBlank(req.extId)) {
            res.statusCode = 400;
            res.responseBody = Blob.valueOf('{"error":"extId required"}');
            return;
        }
        Database.UpsertResult r = Database.upsert(
            new Order__c(Ext_Id__c = req.extId, Status__c = req.status),
            Order__c.Ext_Id__c, false);
        res.statusCode = r.isSuccess() ? 200 : 422;
        res.responseBody = Blob.valueOf(JSON.serialize(r));
    }
}
```

**Hidden gotchas & must-remember points:**
- The class and methods must be `global` and the methods `static`.
- Only one method per HTTP verb per class.
- Unhandled exceptions return 500 with a stack-like message; catch and map errors.
- Wildcard `/*` is allowed only at the end of the path.
- Endpoint is `/services/apexrest/`, not `/services/data/`.
- Test with `RestContext` set up manually in unit tests.

**Best practice:** Keep the class thin: parse and validate, then call a service layer, and return explicit status codes and versioned contracts.

---
Source: ForceChallenges · last updated 2026-11-02
