How can one retrieve images from Salesforce (SF) via its REST API that are embedded as links in RTF fields in custom objects?
We aim to extract information from SF via its REST API in order to generate a report in Word format. To to so we need to run queries into the SF custom objects that contain the relevant information. Typically, we are looking to get this information from a collection of custom objects.
One of the custom fields contains an RTF field which contain links to the relevant images. These images are displayed when the objects are viewed in the SF UI. There are several entries in both StackOverflow and Salesforce:StackExchange regarding this topic. Many of these entries discuss Apex methods. The ones that discuss retrieving the images via the REST API did not allow me to be successful.
An entry in the SF REST API developer guide here instructs us how to achieve this: send a request to the REST API via a GET as follows:
/vXX.X/sobjects/SObjectName/id/richTextImageFields/fieldName/contentReferenceId
The trick here is to determine what is the SObjectName, the id, the fieldName and the contentReferenceId. We can get the names from the SF database schema we are working with. Fortunately, we can get the IDs from the embedded links in the RTF field.
IDs
The embedded links in the RTF field take the following form:
https://[someInternalSalesforceURL].force.com/servlet/rtaImage?eid=a0Y3l00000G31DT&feoid=00N1N00000F14uz&refid=0EM3l0000039EK0
There are three IDs in this link:
We need to use the eid and the refid to contruct the request to the SF REST API as follows:
In the example above:
/vXX.X/sobjects/SObjectName/a0Y3l00000G31DT/richTextImageFields/fieldName/0EM3l0000039EK0
Names
The next step is to review your database schema and work out the SObjectName and the fieldName. The SObjectName is the Name of the custom object that contains the RTF field. Say: myObject__c The fieldName obviously is the name of the RTF field: say myRTFfield__c The request to SF then works out to be:
/vXX.X/sobjects/myObject__c/a0Y3l00000G31DT/richTextImageFields/myRTFfield__c/0EM3l0000039EK0
Retrieving the image
Before sending this to SF you need to prefix it with your salesforce instance URL and you need to articulate the REST API version, e.g. v48.0
Sending this as a GET to SF, I am an R user, returns an object that contains the image as data (in the R case: a matrix). This data object can be converted to an image and saved as a PNG file.
Assumptions
Sample R code
In R this looks something like this:
library(httr)
library(png)
request_headers <- c("Accept" = "application/json",
"Content-Type" = "application/json",
"Authorization" = paste0("Bearer ", access_token))
url <- "/services/data/v48.0/sobjects/myObject__c/a0Y3l00000G31DT/richTextImageFields/myRTFfield__c/0EM3l0000039EK0"
url <- paste0(instance_url, url)
result <- GET(url, add_headers(request_headers))
img <- content(result, type = "image/png")
writePNG(img, "myImage.png")