Sunday, January 16, 2011

Salesforce REST API Read Record

In my last post I showed how to create a new record in Salesforce using the REST API, now lets look at reading a record.
To access a record you need to add the record’s id to the end of the object URI that I showed in the last post. For example to access a specific account record you would use:
The id’s aren’t shown directly when you edit a record in SFDC, but you can find the record id in the URL when you are editing a record. You can also get an id from the response when you create a record as we saw last time.
The code to perform the read will look something like this:

public string ReadData()
var uri = instanceURL + "/services/data/v20.0/sobjects/Account/0017000000hX4Iz";

var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "application/json";
req.Method = "GET";

WebResponse resp;

resp = req.GetResponse();
catch (WebException ex)
resp = ex.Response;

var sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();

This is pretty much the same code we used for the insert but it uses an HTTP GET instead of POST,  and there is no body needed for the request. You will also notice a new header, X-PrettyPrint:1. This will make SFDC return the response in a more readable format with appropriate line breaks and indentation. This header can be used in any of the REST API commands.

The response will contain the JSON formatted Account object. Remember, as always, you can add .xml to the end the URI to have the response returned in XML instead of JSON.

By default this command will return all the fields in the record. You can specify only the fields you want to return like this:,Name

We have added a query string called fields to the URI which lists the fields you want to return.

No comments: