I came across a peculiar requirement recently, wherein we needed to download files in a scheduled job. As you all know downloading a file can be a tricky affair with Salesforce.
Fortunately, using REST API we can achieve it. So, the solution became somewhat easier, wherein we could make a CURL call and download the file.
However, all usual cases reference using login name/ password or some reference using the Connected app (OAuth) route. For my specific use case, I already have a machine setup with SFDX and with target orgs authenticated.
This solution helps just in that case. With command line scripting it is quite easy (for folks who are experienced with the command line). It took some time for me to get it working.
Note: This approach should be chosen after appropriate review/analysis of other approaches, namely, OAuth-based login flows for app authentication.
Tools used
- SFDX - to retrieve auth tokens
- Curl - to make API calls via the command line
- JQ - to parse JSON in the command line
Steps 1 - Get Org Info
This command helps retrieve target org's
sfdx force:org:display -u <TAGET ORG> --json
Result (masked information)
{
"status": 0,
"result": {
"username": "anshul.verma@targetorg.com",
"id": "00D3I00000089ASPUAA",
"connectedStatus": "Connected",
"accessToken": "<AUTH TOKEN>",
"instanceUrl": "https://targetorg.my.salesforce.com",
"clientId": "PlatformCLI",
"alias": "targetorg"
}
}
Steps 2 - Extract auth token
This command uses the previous command and extracts the auth token from the JSON response of the previous command
sfdx force:org:display -u <TARGET ORG> --json | jq '.result.accessToken' -r
Note: JQ allows us to simply parse and extract desired value within JSON data
Result
(shown in multi-line command format for rendering here)
anshul@Anshuls-MacBook-Pro ~ % sfdx force:org:display -u sv_newdev --json |
pipe> jq '.result.accessToken' -r
<SECURE TOKEN>
Step 3 - Fire the CURL command to make request
Fire API request by using auth token within CURL
curl "https://<TARGET ORG>.my.salesforce.com/apex/AccountData?id=0013I0000039NTTQA2"
-H "Authorization: Bearer <AUTH TOKEN>"
Final - Combine all of these into one command
curl "https://<TARGET ORG>.my.salesforce.com/apex/testAccountPDF?id=0013I0000039NTTQA2"
-H "Authorization: Bearer $(sfdx force:org:display -u <TARGET ORG> --json | jq '.result.accessToken' -r)"
This is a small one-liner code that allows you to invoke an API (in this particular case, get code of visualforce page).
Comments
Post a Comment