Saturday, June 30, 2012

Salesforce REST API Read File

In my last post I showed how to upload a file to Salesforce, now lets look at how to read it back. This requires two steps, one to read the document object and a second step to read the actual file data.
Reading the document object is just like reading any other type of object in Salesforce. First we need a class to hold the document object.

public class sfdcDocument
    public string Description { get; set; }
    public string Keywords { get; set; }
    public string FolderId { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Body { get; set; }

Here is the code to retrieve the document object and de-serialize it.

var uri = instanceURL + "/services/data/v24.0/sobjects/Document/015E0000000qhId";

var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "application/json";
req.Method = "GET";
var resp = req.GetResponse();
var sr = new System.IO.StreamReader(resp.GetResponseStream());
var result = sr.ReadToEnd();

// Convert the JSON response into a token object
JavaScriptSerializer ser = new JavaScriptSerializer();
sfdcDocument doc;
doc = ser.Deserialize<sfdcDocument>(result);

First we create the REST URI needed to retrieve the document. We are using the simplest method of reading the document here, by just specifying the id of the document we want to read. There are ways to query by filename but I will cover that at another time. Now we make an HTTP get request, setting the accesstoken to the value we got during the authentication process, then read the response and finally de-serialize it.

The document object contains a field called Body which contains the URI used to retrieve the actual binary file data. Here is the piece of code needed to do that.

System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("Authorization: OAuth " + accessToken);
client.DownloadFile(instanceURL + doc.Body, @"c:\temp2\" + doc.Name );

Here we use a WebClient to simplify reading the file. As always we add the access token, then execute DownloadFile using the instanceURL you got along with the access token, and the Body property of the document to specify the whole URI. We can also use the Name property of the document to get the original filename for the document and save it using the same document name.

No comments: