Sub topic 11
Calling the service and debugging it
This chapter covers how a client reaches a deployed Apex REST service and how to find the cause when a call fails. It assumes you know basic Apex, HTTP methods, headers and status codes, JSON, and how profiles and permission sets work. It also assumes you have already written a @RestResource class like the AccountRestService from earlier chapters.
What a call needs
Every call to an Apex REST service has four parts. If any one is wrong, the call fails before or inside your code.
- A host. Use your My Domain URL, such as
https://MyDomainName.my.salesforce.com. Sandboxes use a different host form, for examplehttps://MyDomainName--sandboxname.sandbox.my.salesforce.com. - A path. Apex REST lives under
/services/apexrest/. YoururlMappingfollows it. WithurlMapping='/v1/Accounts/*'the full path is/services/apexrest/v1/Accounts/001.... - An HTTP method. It must match an annotated method in the class (
@HttpGet,@HttpPost, and so on). - An access token. The caller sends it in the
Authorization: Bearer <token>header. The token belongs to a user. That user's permissions decide what the service can do, as long as the class runs in user mode or with sharing.
The diagram shows why the failure code tells you where to look. Errors in the first four checks come from the platform. Errors after the handler starts come from your code.
Getting an access token
For quick manual tests, the Salesforce CLI is the easiest source of a token. If you have authorized an org, you can read its token and instance URL.
sf org display --target-org my-org --verboseThe output includes an Access Token and an Instance Url. Treat the token like a password. Do not paste it into tickets or commit it to source control.
For real integrations, use an OAuth flow set up on a connected app or external client app. Server-to-server integrations commonly use the client credentials flow or the JWT bearer flow. Each flow returns a token that you send in the same header. The chapter on authentication covers how to choose one. Here, assume you already have a valid token in the ACCESS_TOKEN environment variable.
Calling with curl
The first example reads one Account. It uses the GET handler.
curl -i -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"The -i flag prints the response status line and headers. That is useful because the status code is often the most important clue.
For a POST, set the content type and send a JSON body. The keys must match the parameter names of the Apex method (name and industry in the earlier example).
curl -i -X POST \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "Acme Corp", "industry": "Energy"}' \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/"Because the mapping ends in /*, a path of /v1/Accounts/ matches with an empty last segment. Keep that in mind when a handler reads the record Id from the URI.
Calling from Apex
One org can call another org's Apex REST service from Apex. Use HttpRequest with a Named Credential so the platform manages the endpoint and the authentication for you.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_Org/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX');
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
System.debug(res.getStatusCode() + ' ' + res.getBody());Partner_Org is the name of the Named Credential. Callouts are not allowed after uncommitted DML in the same transaction, so make the call first or move it to an asynchronous job.
The response you should expect
Apex REST sets the Content-Type of the response based on what the method returns. For a returned object or list, the body is JSON. If a method returns a Blob or a String, the platform sends the value as-is. This matters for debugging, because a plain string in the body is not parsed as JSON by the client.
The status code is 200 by default. It changes when your code sets RestContext.response.statusCode, or when an exception escapes your handler.
| Situation | Typical result |
|---|---|
| Handler returns normally | 200 (or the code you set) |
| Handler sets `statusCode = 404` | 404 with whatever body you return |
| Uncaught exception in the handler | 500 with an error message in the body |
| Missing or expired token | 401 `INVALID_SESSION_ID` |
| Wrong HTTP method for the URL | 405 `METHOD_NOT_ALLOWED` |
| No `urlMapping` matches | 404 `NOT_FOUND` |
| Request body cannot be bound to the parameters | 400 or 500 with a parsing message |
An uncaught exception returns a body that exposes the raw error text. In production code, catch exceptions you expect and return a controlled body. Do not let internal messages reach callers.
Debugging with debug logs
A debug log records what Apex did during a request. To use it, add a trace flag for the user whose token you are sending. This is the integration user, not you, unless you are testing with your own token.
- In Setup, open Debug Logs.
- Add a trace flag for the user that owns the token.
- Set a debug level that includes Apex Code at
DEBUGorFINE, and Database atINFO. - Send the request again.
- Open the new log from the list.
With the CLI you can follow logs as they arrive:
sf apex tail log --target-org my-org --colorIn the log, look for these lines first:
CODE_UNIT_STARTEDwith the class name shows that the platform found and started your handler. If the log has no such line, the request never reached your code.USER_DEBUGlines show yourSystem.debugoutput.SOQL_EXECUTE_BEGINandSOQL_EXECUTE_ENDshow each query and its row count.EXCEPTION_THROWNandFATAL_ERRORshow uncaught exceptions with a stack trace.LIMIT_USAGE_FOR_NSat the end shows how close you came to governor limits.
Log what you need to answer the question "what did the handler receive?" Printing the request URI, the HTTP method and the body length is usually enough.
RestRequest req = RestContext.request;
System.debug(LoggingLevel.INFO, req.httpMethod + ' ' + req.requestURI);
System.debug(LoggingLevel.INFO, 'Body size: ' + (req.requestBody == null ? 0 : req.requestBody.size()));Avoid logging full request bodies that may hold personal data. Debug logs are readable by any admin who can open them.
Common failures and their causes
Use the status code and the error text to narrow the cause.
401 Unauthorized
The body usually contains INVALID_SESSION_ID. The token is expired, revoked, copied with extra characters, or sent to the wrong host. A token from a sandbox does not work against production. Check that you use the instance or My Domain URL that issued the token.
403 Forbidden or a "not authorized" message
The user is authenticated but cannot use the class. Grant access to the Apex class through a profile or a permission set that is assigned to the calling user. A missing class grant is the most common cause of a service that works for an admin and fails for an integration user. This error can also come from the connected app, if its OAuth scopes or policies do not allow the user.
404 NOT_FOUND
There are two different causes, and they look the same at first.
- The platform could not match the path. Check the
urlMappingspelling, the case, the version segment (v1), and a missing or extra slash. Remember thaturlMappingis relative to/services/apexrest/. - Your handler returned 404 on purpose, as in
AccountRestServicewhen no row is found. Open the debug log. If you seeCODE_UNIT_STARTEDfor your class, the handler ran and chose 404.
405 Method Not Allowed
The path matched, but the class has no method annotated for that HTTP verb. Each verb can be used by only one method per resource class. Two @HttpGet methods in one class fail at save time.
400 or 500 on a POST
Check the request body and the Content-Type header. Common causes:
- The JSON key names do not match the Apex parameter names exactly.
- The body is not valid JSON, for example because of a trailing comma or single quotes.
- A value has the wrong type, such as a string for a number.
- The header says
application/x-www-form-urlencoded, which curl sends by default with-dif you do not set the type.
500 with a DML or query error
The handler started and then failed. Read EXCEPTION_THROWN in the log. A WITH USER_MODE query or insert as user throws when the calling user lacks object or field access. The exception text names the missing field. Fix it by granting the permission to the integration user, not by removing the enforcement.
Works in Developer Console, fails from the client
Anonymous Apex runs as you, with your permissions and without a RestContext. The client runs as the token's user. Compare the two users' permissions before suspecting the code.
A debugging routine
When a call fails, work in a fixed order. Each step rules out a group of causes.
- Read the status code and body with
curl -i. - If it is 401, fix the token and host. Stop there.
- Confirm the URL path against the
urlMapping. - Check the class access for the calling user.
- Add a trace flag, repeat the request, and look for
CODE_UNIT_STARTED. - If the handler ran, read the log from that line down to the first exception or
USER_DEBUGthat looks wrong. - Reproduce the case in a unit test with a
RestRequest. A test is faster to repeat than a network call.
Exercises
Exercise
A client calls GET /services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX and receives 404. The debug log for the calling user shows no CODEUNITSTARTED line for AccountRestService. What is the likely cause, and what do you check?
Show answer
The platform never ran your handler, so the 404 did not come from your code. Check that the path matches the urlMapping (version segment, spelling, case, slashes), that you are calling the correct org and host, and that the calling user has been granted access to the Apex class.
Exercise
A POST to the service returns a 500 body that says the field Industry is not writable. The same code works when an admin tests it. Where does the difference come from, and how do you fix it?
Show answer
The handler uses insert as user, so it enforces the calling user's field-level security. The integration user lacks edit access to Account.Industry, while the admin has it. Grant that field permission to the integration user through a permission set. Do not remove the enforcement from the code.