I built a REST API in salesforce which allows a third application to make a call to salesforce through POST method and I return the JSON response back based on the Account Name posted. I'm not able to get the session Id which I need for authentication. I'm just looking for a basic authentication. How to query the session id and allow the third part applications to call the apex api.

    global class RestTestController {
    global static void getTestAccount() {
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
    res.addHeader('Content-Type', 'application/json');
    String jsonResponse = '';
    String accountName = req.params.get('account_name');
   // No account_name parameter was found; return status 400
    if(accountName == null) {
        res.statusCode = 400;
        jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter account_name"}}';
        res.responseBody = blob.valueOf(jsonResponse);

// Get the list of accounts that match the account_name sent in the request.
    List<Account> accounts = [SELECT Id, Name, Phone, Fax, Website
                              FROM Account
                              WHERE Name =: accountName];

// No accounts with matching account_name
    if( accounts.isEmpty()) {
        res.statusCode = 400;
        jsonResponse = '{"response": {"status": "Failure", "message": "No account matching account_name was found"}}';
        res.responseBody = blob.valueOf(jsonResponse);

// At least 1 account was found, JSON serialize it and send it back.
    try {
        res.statusCode = 200;
        jsonResponse = Json.serialize(accounts[0]);
        res.responseBody = blob.valueOf(jsonResponse);
    } catch ( Exception ex ) {
        res.statusCode = 500;
        jsonResponse = '{"response": {"status": "Failure", "message": "' + ex + '"}}';
        res.responseBody = blob.valueOf(jsonResponse);

Your (presumably external to Salesforce) application will need to obtain the session ID by first authenticating with Salesforce. Once the authentication is complete you will be returned a session ID (AKA an access token) that can then be included in the request to your REST API. See e.g. Understanding Authentication.

Getting the authentication logic right is typically trickier than implementing the REST API. Plan for this to take several hours of research followed by probably rather more hours of configuration/coding/testing.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.