I found this answer for getting terms using JSOM. Is there a way of doing this using REST?
2 Answers
SharePoint 2013 does not support managing term set using REST API still now. In that case, JSOM is the one and only way. If your requirement is just to read the term set, then you can follow this.
module.getTermSet = function (id, callback) {
SP.SOD.loadMultiple(['sp.js'], function () {
// Make sure taxonomy library is registered
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.loadMultiple(['sp.taxonomy.js'], function () {
var ctx = SP.ClientContext.get_current(),
taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx),
termStore = taxonomySession.getDefaultSiteCollectionTermStore(),
termSet = termStore.getTermSet(id),
terms = termSet.getAllTerms();
ctx.load(terms);
ctx.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
callback(terms);
}),
Function.createDelegate(this, function (sender, args) { }));
});
});
};
You could build your own REST service with Web API that gets the terms using CSOM and returns JSON. Call the API from SharePoint via jQuery $.ajax. Here's an example that includes parent and child objects:
[DataContract]
public class TermInfo
{
[DataMember]
public Guid Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public TermInfo Parent { get; set; }
[DataMember]
public TermInfo[] Children { get; set; }
[DataMember]
public string Url { get; set; }
}
[HttpGet]
[AllowAnonymous]
[Route("intranet/navigation")]
public IEnumerable<TermInfo> GetNavigation()
{
//TermInfo
List<TermInfo> results = new List<TermInfo>();
using (var ctx = new ClientContext("http://yoursharepointsite"))
{
var taxonomySession = TaxonomySession.GetTaxonomySession(ctx);
var termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
var allTerms = termStore.GetTermSetsByName("Intranet Navigation", 1033);
var termSet = allTerms.GetByName("Intranet Navigation");
var terms = termSet.GetAllTerms();
ctx.Load(terms, includes => includes.Include(i => i.Id, i => i.Name, i => i.Parent, i => i.Parent.Id, i => i.Parent.Name, i => i.IsRoot, i => i.LocalCustomProperties));
ctx.ExecuteQuery();
foreach (var term in terms)
{
var terminfo = new TermInfo { Id = term.Id, Name = term.Name };
if (term.LocalCustomProperties.Keys.Contains("_Sys_Nav_SimpleLinkUrl"))
{
terminfo.Url = term.LocalCustomProperties["_Sys_Nav_SimpleLinkUrl"];
}
if (!term.IsRoot)
{
var parent = terms.FirstOrDefault(t => t.Id == term.Parent.Id);
terminfo.Parent = new TermInfo{ Name = parent.Name, Id = parent.Id };
}
results.Add(terminfo);
}
}
//Go back through and add children
foreach(var item in results)
{
var children = results.Where(x => x.Parent != null && x.Parent.Id == item.Id);
if (children.Count() > 0)
{
item.Children = children.ToArray();
}
}
return results;
}//navigation