Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Integration and Deployment

Exposing Apex as a REST Service with @RestResource

Build a custom REST endpoint in Apex with @RestResource, @HttpGet, @HttpPost, RestContext, status codes and tests, with a runnable Java router stand-in.

The last lesson called other people's APIs. Now the other direction: an external system wants to call you. Salesforce already has a standard REST API for records, but sometimes you need a custom endpoint, for example "create an order with its line items in one request" or "return a score computed by Apex". Apex exposes this with the @RestResource annotation. This lesson shows how, including security and tests. It pairs with REST callouts.

Apex REST needs an org, so Apex listings are read-only. The runnable examples are Java stand-ins: a tiny router and a JSON-building handler that model the same request flow.

A first endpoint

APEX
@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 WITH USER_MODE];
    }

    @HttpPost
    global static Id createAccount(String name, String industry) {
        Account a = new Account(Name = name, Industry = industry);
        insert as user a;
        return a.Id;
    }
}

Rules:

  • The class is global and carries @RestResource(urlMapping='...'). The mapping is case-sensitive and may end with a wildcard *.
  • Methods are global static. Annotate with @HttpGet, @HttpPost, @HttpPut, @HttpPatch or @HttpDelete. Only one method per verb per class.
  • The full URL is https://MyDomain.my.salesforce.com/services/apexrest/accounts/<id>.
  • Callers authenticate with an OAuth access token (usually via a Connected App or External Client App) and the user's permissions apply, which is why with sharing and WITH USER_MODE matter.
  • Arguments of a @HttpPost method are filled from the JSON body, matching by parameter name.

RestContext: the request and the response

When you need more control, use RestContext instead of parameters:

APEX
@HttpPost
global static void createOrder() {
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;

    OrderPayload payload;
    try {
        payload = (OrderPayload) JSON.deserialize(req.requestBody.toString(), OrderPayload.class);
    } catch (JSONException e) {
        res.statusCode = 400;
        res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, String>{ 'error' => 'Invalid JSON' }));
        return;
    }

    // ... validate and insert, then:
    res.statusCode = 201;
    res.addHeader('Content-Type', 'application/json');
    res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, Object>{ 'id' => 'a01xx0000000001' }));
}

A void method with RestContext.response lets you set the status code and body explicitly. Returning an object makes Salesforce serialize it to JSON with status 200; an uncaught exception returns 500.

Good API habits

  1. Return the right status code: 200 OK, 201 Created, 400 Bad Request for invalid input, 404 Not Found, and 409 for conflicts. Do not return 200 with an error message.
  2. Validate input and return a clear JSON error body. Never leak stack traces.
  3. Be bulk-friendly: accept a list when clients may send many records, and use one DML statement.
  4. Version your URL: urlMapping='/v1/orders/*', so you can introduce /v2 without breaking callers.
  5. Idempotency: for POSTs that clients may retry, accept an external id and use upsert.
  6. Keep logic out of the resource class: the endpoint parses and responds; a service class does the work and has its own tests.

Testing a REST resource

Create a RestRequest, set it on RestContext, call the method directly:

APEX
@isTest
static void postCreatesAccount() {
    RestRequest req = new RestRequest();
    req.requestURI = '/services/apexrest/accounts/';
    req.httpMethod = 'POST';
    RestContext.request = req;
    RestContext.response = new RestResponse();

    Id newId = AccountRestService.createAccount('Rest Co', 'Energy');

    Assert.isNotNull(newId);
    Assert.areEqual('Rest Co', [SELECT Name FROM Account WHERE Id = :newId].Name);
}

Try the idea: a router with status codes (Java stand-in)

Java Stand-in: route a request to a handler and return a status (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each call returns an honest status code instead of always 200.

Try the idea: keeping the endpoint thin (Java stand-in)

Java Stand-in: the resource parses, the service decides (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Security checklist

  • Run with sharing and enforce field-level security (WITH USER_MODE, insert as user).
  • Give the integration user a permission set with only what the endpoint needs.
  • Do not trust IDs from the client without a query filtered by the current user.
  • Remember callers must call from an allowed network and with a valid token; Salesforce enforces this, not your class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the base URL path for Apex REST resources?

    Custom Apex REST endpoints are served under /services/apexrest followed by your urlMapping.
  2. 2. How many methods per HTTP verb may one @RestResource class define?

    Each verb annotation (@HttpGet, @HttpPost and so on) can be used on only one method in the class.
  3. 3. Which status code best tells the client that a record was created?

    201 Created signals a new resource; 200 is a generic success.
  4. 4. Why keep the logic out of the @RestResource class?

    The resource should translate HTTP to a service call; business logic belongs in a reusable, testable class.

Summary

  • @RestResource(urlMapping) plus @HttpGet/@HttpPost/... on global static methods publishes an endpoint under /services/apexrest.
  • Use RestContext for status codes, headers and raw bodies.
  • Return honest status codes, version the URL, and keep endpoints thin and secure.
  • Test by building a RestRequest and calling the method.

Next: Deploying Apex and LWC with the Salesforce CLI