Get All content types from ContentTypeHub using SharePoint Rest API v2 using JavaScript

Why get the content type from Content Type Hub(CTH)?

Content Type Hub is a centralized location where we manage and publish content types to other web applications. Content Type Hub is actually a Site Collection. 
"In simple words, it is one place where you get to manage all the content type present in a tenant."
To get all the Content Type from ContentTypeHub using REST API V2.* becomes easy now. It involves only the following two steps:
  • Get the site ID of the ContentTypeHub
    • https://{YourtenantURL}/sites/contentTypeHub/_api/site
  • Get all content types
    • https://{YourtenantURL}/_api/v2.1/sites/{siteID of ContentTypeHub}/contentTypes
Step 1:

I am getting the site ID of the ContentTypeHub by calling the REST API. As this is still from V1.0 endpoint, after '/api' , there is no need to mention the endpoint version. 

In the success method, I am calling the method getAllContentTypes which will get the content types.

  1. var siteURL=_spPageContextInfo.siteAbsoluteUrl;  
  2. var rootURL= siteURL.substring(0,siteURL.indexOf("/sites"));  
  3. $.ajax({  
  4.     url: rootURL +"/sites/contentTypeHub/_api/site",  
  5.     method: "GET",  
  6.     headers: {  
  7.         "Accept""application/json",  
  8.         "Content-Type""application/json"  
  9.     },  
  10.     success: function(data) {  
  11.        let siteID= data.Id;  
  12.         getAllContentTypes(siteID);  
  13.     },  
  14.     error: function(data) { 
  15.         alert("Error: " + data);   
  16.     }  
  17. });  

Step 2:

Now that we have the site unique GUID from step 1, we can get all the content types using the V2.* endpoint. Here, we need to mention the version after '/api'. The endpoint returns all the content type present in the tenant.

  1. function getAllContentTypes(siteID){  
  2.     $.ajax({  
  3.     url: rootURL +"/_api/v2.1/sites/"+siteID +"/contentTypes",  
  4.     method: "GET",  
  5.     headers: {  
  6.         "Accept""application/json",  
  7.         "Content-Type""application/json"  
  8.     },  
  9.     success: function(data) {  
  10.         let allContentType= data.value;  
  11.         console.log(allContentType);      
  12.     },  
  13.     error: function(data) {
  14.         alert("Error: " + data);  
  15.     }  
  16. });  
  17. }  


Popular posts from this blog

Save Location details to SharePoint Location column through SPFx and PnP JS

How To Create/ Generate QRcode In SPFx Web Part