SP.Taxonomy.TaxonomyFieldValue
type exposes the following properties via SharePoint REST API:
How to retrieve Taxonomy field values using SharePoint REST in JavaScript
Assume Pages
library contains:
Category
single valued taxonomy field
Categories
mutli-valued taxonomy field
Then the following example demonstrates how to perform GET request to retrieve taxonomy field values:
function getJson(url,success,failure)
{
$.ajax({
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
url: url,
success: success,
failure: failure
});
}
function getListItems(listTitle,success,failure)
{
var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listTitle + "')/items";
getJson(endpointUrl,
function(data){
success(data.d.results);
},
failure);
}
//Usage
getListItems('Pages',
function(items){
//print info
for(var i = 0; i < items.length; i++) {
console.log(items[i].Category.Label); //single-valued taxonomy field
if(items[i].Categories.results.length > 0)
console.log(items[i].Categories.results[0].Label); //print first value of multiple taxonomy field
}
},
function(error){
console.log(JSON.stringify(error));
}
);
But unfortunately there is a known bug with retrieving a Label from single-valued taxonomy field using SharePoint REST GET request.
The workaround is to perform POST request to retrieve taxonomy field values as demonstrated below:
function postJson(endpointUrl,payload,success,failure)
{
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(payload),
url: endpointUrl,
success: success,
failure: failure
});
}
function getListItems(listTitle, queryViewXml,success,failure)
{
var queryPayload = {
'query':{
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml': queryViewXml
}
};
var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
postJson(endpointUrl,queryPayload,
function(data){
success(data.d.results);
},failure);
}
//Usage
getListItems('Pages','<View><Query/></View>',
function(items){
//print info
for(var i = 0; i < items.length; i++) {
console.log(items[i].Category.Label); //single-valued taxonomy field
if(items[i].Categories.results.length > 0)
console.log(items[i].Categories.results[0].Label); //print first value of multiple taxonomy field
}
},
function(error){
console.log(JSON.stringify(error));
});