The code example shows how to make SharePoint REST API GET calls in C# using HttpWebRequest. The sample code assumes that the SharePoint List is accessible to anonymous ueres, hence no credentials are passed.
The code uses Newtonsoft.Json Nuget package to parse the REST response.
Since there is a 100 item limit, the code uses __next property of the response to get the paged data.
Usage:
References: Working With SharePoint 2013 REST API in a C# Managed Code
The code uses Newtonsoft.Json Nuget package to parse the REST response.
Since there is a 100 item limit, the code uses __next property of the response to get the paged data.
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
namespace SPREST
{
public class RESTUtility
{
public static JArray GetListData(string webUrl, string listUrl, string query)
{
JArray listData = new JArray();
try
{
webUrl = webUrl.TrimEnd('/');
string endPoint = string.Format("{0}/_api/web/GetList('{1}')/items?{2}", webUrl, listUrl, query);
do
{
var nextData = GetListData(endPoint);
endPoint = nextData.Item2;
listData.Merge(nextData.Item1);
} while (!string.IsNullOrEmpty(endPoint));
}
catch (Exception ex)
{
// Handle Error
}
return listData;
}
private static Tuple<JArray, string> GetListData(string endPoint)
{
JArray listData = null;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Method = "GET";
req.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)req.GetResponse();
using (WebResponse wResponse = req.GetResponse())
using (Stream readStream = wResponse.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(readStream))
{
string response = responseReader.ReadToEnd();
JObject jObj = JObject.Parse(response);
listData = (JArray)jObj["d"]["results"];
if (jObj["d"]["__next"] != null)
{
endPoint = jObj["d"]["__next"].ToString();
}
else
{
endPoint = null;
}
}
}
return new Tuple<JArray, string>(listData, endPoint);
}
}
}
Usage:
var listItems = RESTUtility.GetListData("http://sp2013/sites/team", "/Lists/TestList",
"$select=Title,Location&$orderby=Title");
foreach (var item in listItems)
{
string title = item["Title"]?.ToString(),
string location = item["Location"]?.ToString()
}
References: Working With SharePoint 2013 REST API in a C# Managed Code