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.SharePoint-2013-Hosting 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).


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.

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.