Filter Documents From SharePoint Libraries By MetaData Using REST API

Introduction
 
In this blog, you will see how to filter out the documents from SharePoint document libraries, using metadata tags filters with the help of REST API calls.
 
Building CAML query
 
The items can be filtered, using filter queries but when it comes to metadata tags, the querying the document libraries will be bit complicated. The CAML query is passed, using REST API with POST method to get the actual documents.
 
CAML query looks, as shown below.
  1. '<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="TaxKeyword"/><Value Type="TaxonomyFieldType">sharepoint</Value></Eq></Where></Query></View>';  
The code snippet given below shows the data retrieval, using REST API with the help of CAML query. 
  1. var thisUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Documents')/GetItems";  
  2. var caml = '<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="TaxKeyword"/><Value Type="TaxonomyFieldType">sharepoint</Value></Eq></Where></Query></View>';  
  3. $.ajax({  
  4.     url: thisUrl,  
  5.     type: "POST",  
  6.     headers: {  
  7.         "Accept""application/json; odata=verbose",  
  8.         "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  9.         "Content-Type""application/json; odata=verbose"  
  10.     },  
  11.     data: JSON.stringify({"query": { "__metadata": { "type""SP.CamlQuery" }, "ViewXml": caml}}),            
  12.     success: function (data){  
  13.         // data.d will yield the required results  
  14.     },  
  15.     error: function (data){  
  16.         console.log("Error in query");            
  17.     }  
  18. });