Console Application To Fetch SharePoint List Data Using REST API With CAML Query In C# Managed Code

Introduction

SharePoint 2013 has many restful APIs to fetch the data from lists. However, sometimes, we need to use a CAML query to filter out the data. SharePoint Rest API has an option to pass a CAML query as data to an API call. The below steps will help you to call a Rest API with CAML query filtering.

In addition, this article will help you to understand how to call REST API POST methods in console applications using C# managed code.

The below example calls a REST API to retrieve the data from Department SharePoint list. Department list has a Title column, which refers to the department name. CAML query will be used to filter the Department list data by Title (Department name).

SharePoint

 

REST endpoint

/_api/web/lists/getbytitle('Department')/GetItems

CAML Query Structure

CAML query structure should be strictly followed as below:

<View><Query> <CAML_Query> </Query></View>

Assembly References

  1. Net: To make a request to a Uniform Resource Identifier (URI). 
  2. Web.Script.Serialization: For serialization and deserialization functionality
  3. IO: For reading and writing streams.

Request Header for POST Request

The API endpoint is of type POST. Hence, the REST header should be same as other post requests,

  1. oWebRequest.Accept = "application/json;odata=verbose";  
  2. oWebRequest.ContentType = "application/json;odata=verbose";  
  3. oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());  
  4. oWebRequest.ContentLength = stringData.Length;  

Steps

Please follow the below steps to create a console application:

  1. Open Visual Studio.
  1. Select Console Application template and provide a suitable name.
  1. Add required assemblies.
  1. Add the below code in Program.cs file.
  1. Run the code.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Net;  
    5. using System.Web.Script.Serialization;  
    6.   
    7. namespace ConsoleApp1  
    8. {  
    9.     class Program  
    10.     {  
    11.        
    12.         static void Main(string[] args)  
    13.         {  
    14.             string sConnStr = "<web_url>";  
    15.             Uri oUri = null;  
    16.             oUri = new Uri(sConnStr + "/_api/web/lists/getbytitle('Department')/GetItems");  
    17.   
    18.             string sResult = string.Empty;  
    19.   
    20.             string stringData = "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";  
    21.   
    22.             HttpWebRequest oWebRequest = (HttpWebRequest)WebRequest.Create(oUri);  
    23.             oWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;  
    24.             oWebRequest.Method = "POST";  
    25.             oWebRequest.Accept = "application/json;odata=verbose";  
    26.             oWebRequest.ContentType = "application/json;odata=verbose";  
    27.             oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());  
    28.             oWebRequest.ContentLength = stringData.Length;  
    29.   
    30.             StreamWriter writer = new StreamWriter(oWebRequest.GetRequestStream());  
    31.             writer.Write(stringData);  
    32.             writer.Flush();  
    33.   
    34.             WebResponse wresp = oWebRequest.GetResponse();  
    35.             using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))  
    36.             {  
    37.                 sResult = sr.ReadToEnd();  
    38.             }  
    39.         }  
    40.         public static string GetFormDigest()  
    41.         {  
    42.             string sFormDigest = null;  
    43.             string sConnStr = "<web_url>";  
    44.             Uri oUri = null;  
    45.             oUri = new Uri(sConnStr + "/_api/contextinfo");  
    46.               
    47.             HttpWebRequest oWebRequest = HttpWebRequest.Create(oUri) as HttpWebRequest;  
    48.             oWebRequest.UseDefaultCredentials = true;  
    49.             oWebRequest.Method = "POST";  
    50.             oWebRequest.Accept = "application/json;odata=verbose";  
    51.             oWebRequest.ContentLength = 0;  
    52.             oWebRequest.ContentType = "application/json";  
    53.             string sResult;  
    54.             WebResponse sWebReponse = oWebRequest.GetResponse();  
    55.   
    56.             using (StreamReader sr = new StreamReader(sWebReponse.GetResponseStream()))  
    57.             {  
    58.                 sResult = sr.ReadToEnd();  
    59.             }  
    60.   
    61.             var jss = new JavaScriptSerializer();  
    62.             var val = jss.Deserialize<Dictionary<string, object>>(sResult);  
    63.             var d = val["d"] as Dictionary<string, object>;  
    64.             var wi = d["GetContextWebInformation"] as Dictionary<string, object>;  
    65.             sFormDigest = wi["FormDigestValue"].ToString();  
    66.   
    67.             return sFormDigest;  
    68.   
    69.         }  
    70.     }  
    71. }  

Code Explanation

  1. The complete data to be passed in the request will be:
    1. "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";  
  1. Form Digest need to be passed while calling post method. GetFormDigest() returns the required request digest.

Summary

In this article, we have explored how to call SharePoint REST API with CAML query in C# console application. The CAML query can also be passed through the URL itself. However, this makes the API URL complicated and sometimes, restricts the length of the URL. The same code can be used in implementing custom APIs as well.

Happy Reading!