SharePoint REST API - CAML Query

Introduction

Last week I was working with SharePoint rest API. In some terms, I needed to do some complicated query in a SP list. To do these queries I prefer CAML. But to use CAML with SharePoint rest API, I have been banging my head against the wall for a couple of days as I was stacked with errors. At last I got the solution I wanted.

Using the code

So, what I missed, is the first condition of using CAML with rest request. That is, it always has to be a POST request. The request header is as same as the other normal post request for SharePoint Rest API.

  1. headers: {  
  2.               "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  3.               'content-type''application/json;odata=verbose',  
  4.               'accept''application/json;odata=verbose'  

The REST endpoint for using caml query is
  1. /_api/web/lists/GetByTitle('<List Name>')/GetItems  

The complete code with the rest call is given bellow:

  1. // Include JQuery reference   
  2. // ... script continues ...   
  3.   
  4. /// List Name and CAML Query as Parameter  
  5. function restCallwithCaml(listName, caml) {  
  6.     /// get the site url  
  7.     var siteUrl = _spPageContextInfo.siteAbsoluteUrl;  
  8.     /// set request data  
  9.     var data = { "query" :{"__metadata": { "type""SP.CamlQuery" }, "ViewXml": caml}};  
  10.     /// make an ajax call  
  11.     $.ajax({  
  12.        url: siteUrl+"/_api/web/lists/GetByTitle('"+ listName +"')/GetItems",  
  13.             method: "POST",  
  14.             data: data,  
  15.             headers: {  
  16.                "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  17.                'content-type''application/json;odata=verbose',  
  18.                'accept''application/json;odata=verbose'  
  19.             }  
  20.             success: function (response) {  
  21.             ///do your code  
  22.             },  
  23.             error: function (data) {  
  24.             ///do your code  
  25.            }  
  26.     });  

The CAML Query has to be used in between this <View><Query>…CAML Query…</Query></View> tag. The query with the way to call the function is given below:
  1. var caml = “<View><Query><Where><Eq><FieldRef Name='EndDate'/><Value Type='DateTime'><Today /></Value></Eq></Where></View></Query>”;
  2. restCallwithCaml(<listName>, caml); 
Points of Interest

The CAML query can also be used in query string of the rest request. But it makes the URL unnecessarily complicated. If anyone knows of any better approach, please let me know in the comments below and I will update my article.