I have a test class of REST API and I want check this. In workbench it is OK, but now I want check and use with other application. Can I check this class? I have tried with cURL, but I do not get it; I get an error: {"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}


global with sharing class Test_RestAPI {
    global static String getAccountId() {
        RestRequest request = RestContext.request;
        String toRet = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        return '123';


enter image description here

  • 1
    Juan, are you trying to write an Apex test for this class, or just trying to validate with an API client other than Workbench? If the latter, you need to provide a session id in your headers.
    – David Reed
    Commented Jan 23, 2019 at 16:56
  • Hi David. I am trying to validate with an API client. Sorry, not understand "you need to provide a session id in your headers". Thanks Commented Jan 23, 2019 at 17:21

2 Answers 2


To be able to invoke a REST API exposed from Salesforce from external applications, there are some pre-requisite that needs to be followed. You will need to set the "access token" with your request to be able to call the REST API. Below are the steps those are required:

  1. You will need to create a connected app, share the client secret/key to the external system
  2. The external system authenticates themselves using OAuth 2.0 and gets the access token
  3. Use the access token, set that in the header of the request and then invoke the API

You can follow the steps as outlined in this documentation. As an example, how to do this, I have steps outlined in one of my blog posts using POSTMAN, if that helps.


Calling a Salesforce Apex REST endpoint requires an authenticated session, except in the case that the endpoint is exposed via a public Force.com Site.

When you test in Workbench, you're already authenticated to Salesforce, and Workbench provides the required authentication header. If you're not using Workbench, you'll need to handle authentication yourself, extract the Session Id, and provide it in an Authorization: Bearer <session id here> header.

There's a good example here in the Salesforce REST API documentation. The authentication process doesn't differ here because you're using a custom REST endpoint. You execute the Username-Password OAuth flow in CURL, after setting up a Connected App :

curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=myclientid" -d "client_secret=myclientsecret" -d "[email protected]" -d "password=mypassword123456"

(Note that in a sandbox you'd be using test.salesforce.com).

That'll net you a session Id you can provide to curl with -H:

curl https://instance_name.salesforce.com/services/apexrest/Account -H 'Authorization: Bearer access_token'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .