Sunday, July 26, 2020

Salesforce Object Query via REST Call


Summary

This post explains how to execute a Salesforce Object Query Language (SOQL) command from a REST call.  The approach and code here are by no means production grade.  This is simply a method to get testing jump-started.

SFDC-side Set Up

You will need to create a 'Connected App' that can be accessed via a 'password' OAuth grant type.  Instructions for that here.  Screen-shot below of the critical areas that need to be set for the authentication to work correctly.

As mentioned in the Summary, there's little regard for security in the config below.  These settings are just to get things working.  You can lock it down after that.  You would not use a password OAuth grant type in a production setting.



 

Fetch Access Token

This step was actually the most painful of the entire exercise.  The 'connected app' and HTTP POST have to be configured just right.

function formEncode(data) {
    return Object.keys(data)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
    .join('&');  
}

async function getToken() {
    const body = {
        grant_type: 'password',
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        username: USERNAME,
        password: PASSWORD
    };

    const response = await fetch(AUTH_URL, {
        method: 'POST',
        body: formEncode(body),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
    })
    if (response.ok) {
        const json = await response.json();
        return json.access_token;
    }
    else {
        const msg = `getToken() response status: ${response.status} ${response.statusText}`;
  throw new Error(msg);
    }
}

SOQL Command via REST

Once the access token is obtained, a SOQL command can be URI encoded and sent as a query parameter in a HTTP GET to the URL of your SFDC instance.

async function sendQuery(query, token) {

    const response = await fetch(QUERY_URL + encodeURIComponent(query), {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    if (response.ok) {
        return await response.json();
    }
    else {
        const msg = `sendQuery() response status: ${response.status} ${response.statusText}`;
  throw new Error(msg);
    }

}

Execution

Example of the two functions above being used in a promise chain to execute a SOQL command:
const QUERY='SELECT Name,Phone FROM Account ORDER BY Name';
(() => {
    getToken()
    .then((token) => {
        return sendQuery(QUERY, token);
    })
    .then((data) => {
        console.log(JSON.stringify(data, null, 4));
    })
    .catch((err) => {
        console.error(err);
    });
})();

{
    "totalSize": 12,
    "done": true,
    "records": [
        {
            "attributes": {
                "type": "Account",
                "url": "/services/data/v20.0/sobjects/Account/0013t00001Xq9bnAAB"
            },
            "Name": "Burlington Textiles Corp of America",
            "Phone": "(336) 222-7000"
        },
        {
            "attributes": {
                "type": "Account",
                "url": "/services/data/v20.0/sobjects/Account/0013t00001Xq9bpAAB"
            },
            "Name": "Dickenson plc",
            "Phone": "(785) 241-6200"
        },

Source

https://github.com/joeywhelan/soql

Copyright ©1993-2024 Joey E Whelan, All rights reserved.