SharePoint REST API C#

SharePoint Online External List

In this blog post, I’ll show how to use SharePoint REST API, in a C# console application i.e., .NET server side, to fetch ListItems from a SharePoint Online List.

Just like JavaScript, we can invoke REST calls directly from a .NET C# application, here using HTTPClient.

In the following code snippet, I am fetching the first ListItem of a SharePoint Online’s external list. The output of this call will be a JSON string.

C#

private static async Task<string> RESTCall()
{
	string RESTURL = "{0}/_api/web/lists/GetByTitle('ODataList_Manual')/items?$top=1";
	string webUrl = "https://domain.sharepoint.com";
	string USER = "piyush@domain.onmicrosoft.com";
	var passWord = new SecureString();
	string PWD = "yourPassword";
	PWD.ToList().ForEach(passWord.AppendChar);

	var credential = new SP.SharePointOnlineCredentials(USER, passWord);

	using (var handler = new HttpClientHandler() { Credentials = credential })
	{
		//Get authentication cookie
		Uri uri = new Uri(webUrl);
		handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

		//Invoke REST API 
		using (var client = new HttpClient(handler))
		{
			client.DefaultRequestHeaders.Accept.Clear();
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
			response.EnsureSuccessStatusCode();

			string jsonData = await response.Content.ReadAsStringAsync();

			Debug.Write(jsonData);

			return jsonData;
		}
	}
}

Output

{
	"odata.metadata": "https://domain.sharepoint.com/_api/$metadata#SP.ListData.ODataList_x005f_ManualListItems",
	"value": [{
		"odata.type": "SP.Data.ODataList_x005f_ManualListItem",
		"odata.id": "e2dcb7f0-304c-4b4f-a291-f60b8e15b80a",
		"odata.editLink": "Web/Lists(guid'5d80cee7-8ce4-4201-b172-a6d16ddbf953')/GetItemByStringId('__cg410013000300230043008300g800013001300')",
		"FileSystemObjectType": 0,
		"Id": 0,
		"ServerRedirectedEmbedUrl": "",
		"BdcIdentity": "__cg410013000300230043008300g800013001300",
		"OrderID": 10248,
		"ProductID": 11,
		"UnitPrice": "14.0000",
		"Quantity": 12,
		"Discount": 0.0
	}]
}

Key Takeaways

  • I am using the OData Top System Query Option ($top), to limit the number of returned items to one. For SharePoint, we can achieve the same by passing an empty CAML query, with RowLimit option set to one.
  • I am running this code from a C# console application. I just need to reference the SharePoint Client dll in order to get the definition of SharePointOnlineCredentials.
  • In the output JSON, value attribute is of type array. For multiple items, it will contain as many JSON objects. However, as I have requested only a single item here, this attribute, for this particular case, only contains a single object.

2 thoughts on “SharePoint REST API C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s