REST was introduced in SharePoint 2013, so there are some areas which Microsoft have not covered.
If you guys prefer REST (like me) you would have faced some issues while filtering multivalued taxonomy fields, and like filtering based on user, where is user is added through a group and so on.
I had to go with CSOM to achieve above tasks. But while exploring on REST, I saw a very powerful way to query lists. Like using this you can pass CAML queries into your REST call
There are couple of reasons why I am interested in this approach of getting stuff done.
1. There are many solutions, frameworks which can be used to build complex queries easily.
2. oData operators is somewhat limited in SharePoint when compared to CAML, liked I faced in above mentioned issues.
3. I prefer CAML query than oData operators.
Coming to the code, there are two ways I know off actually. The first option is to embed the query in the query string of a GET call. The other option, which we will use in this post, is to embed the query in the body of a POST call.
var _RequestExecutor = new SP.RequestExecutor(webUrl);
_RequestExecutor.executeAsync({
url: "http://webUrl/_api/web/lists/getbytitle('My list')/GetItems",
method: 'POST',
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
},
body: {
"query": {
"__metadata": {
"type": "SP.CamlQuery"
},
"ViewXml": "<View>" +
"<Query>" + query + "</Query>" +
"</View>"
}
},
success: function (data) {
alert("Success!!");
},
error: function (err) {
alert(JSON.stringify(err));
}
});
Here are the important things about it:
• A REST request with a CAML query is always a POST request.
• A REST request with a CAML query has always to have X-RequestDigest http header (actually because it is a POST request).
• A REST request with a CAML query should always have the attached CAML query in the request body (and not in a query string). We don’t want to mess with long urls, do we?
• A REST request with a CAML query must have the http header “Content-Type: application/json;odata=verbose” unless you use xml in the request body.
No comments:
Post a Comment