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.
- headers: {
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- 'content-type': 'application/json;odata=verbose',
- 'accept': 'application/json;odata=verbose'
- }
- /_api/web/lists/GetByTitle('<List Name>')/GetItems
The complete code with the rest call is given bellow:
- // Include JQuery reference
- // ... script continues ...
- /// List Name and CAML Query as Parameter
- function restCallwithCaml(listName, caml) {
- /// get the site url
- var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
- /// set request data
- var data = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": caml}};
- /// make an ajax call
- $.ajax({
- url: siteUrl+"/_api/web/lists/GetByTitle('"+ listName +"')/GetItems",
- method: "POST",
- data: data,
- headers: {
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- 'content-type': 'application/json;odata=verbose',
- 'accept': 'application/json;odata=verbose'
- }
- success: function (response) {
- ///do your code
- },
- error: function (data) {
- ///do your code
- }
- });
- }
- var caml = “<View><Query><Where><Eq><FieldRef Name='EndDate'/><Value Type='DateTime'><Today /></Value></Eq></Where></View></Query>”;
- restCallwithCaml(<listName>, caml);
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.

Sahil JhambPosted Nov 10, 2017, 3:40 AM
Maybe the - "data : data", attribute would be "body:data".