Retrieve SFDC Attachments using REST

Salesforce changed the way files are managed with Lightning Spring 17′ release, and this introduced a more elaborate procedure to reach the files from external systems. The API call is not as straight-forward as retrieving the ‘body’ to get file content (which was the case earlier).

We will discuss a bit about how to retrieve the files using SFDC APIs. I will be using Javascript to demonstrate, but the API calls should remain similar elsewhere.

Before jumping in the code for API call, explore how the content is stored. Check out how Contact attachment data is stored.

salesforce notes and attachments

Create a SFDC Connected App, and prepare your REST client. Send a post request to authenticate, which will get you the authentication token (access_token) and the instance URL (instance_url) – make note of them. (instructions are in the previously linked post)

Once authenticated, point the URL to do a get request.

ContentDocumentId field in ContentDocumentLink stores the file references associated with the parent entity. I have three files against this contact, and I see three records in the query output. Collect ‘ContentDocumentId’ attribute from the output.

ContentDocument stores the file relationships & references, while ContentVersion object stores the versions and the file content references. Initiate a get request to –

sfdc rest api for attachments contentversion

You could click on the VersionData link to send another request to retrieve the actual file content. For e.g.:

The data you is in base64 encoding and direct view may not make sense. Workbench lets you download the actual file if you had used the same get operation as above, but would need you to repeat the clicks for each file record.

Simple Javascript Utility to Get SFDC Files

The below script merges all the above operations. It is written in Javascript and tested in Windows using node.

 

How to use the script?

  1. Install node if you don’t have that on your computer (no node? what kind of specimen are you?)
  2. Install cross-fetch that allows you to use fetch for API calls.

    You could do this with XMLHttpRequest, but where’s the fun in that
  3. Ensure your NODE_PATH refers to global modules. The simplest way to do that is to edit ‘Environment Variables’ and set NODE_PATH to “%AppData%\npm\node_modules”
  4. Copy/paste the above code in get-sfdc-files-contact.js
  5. Open command prompt and execute “node get-sfdc-files-contact.js”
  6. The script will create a sub-directory and store all files with name as “<fileId> + <SFDCFileName>”

Found an error? Submit a pull request on GitHub.

Leave a Reply

avatar
  Subscribe  
Notify of