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.
- var siteURL=_spPageContextInfo.siteAbsoluteUrl;
- var rootURL= siteURL.substring(0,siteURL.indexOf("/sites"));
- $.ajax({
- url: rootURL +"/sites/contentTypeHub/_api/site",
- method: "GET",
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- },
- success: function(data) {
- let siteID= data.Id;
- getAllContentTypes(siteID);
- },
- error: function(data) {
- alert("Error: " + data);
- }
- });
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.
- function getAllContentTypes(siteID){
- $.ajax({
- url: rootURL +"/_api/v2.1/sites/"+siteID +"/contentTypes",
- method: "GET",
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- },
- success: function(data) {
- let allContentType= data.value;
- console.log(allContentType);
- },
- error: function(data) {
- alert("Error: " + data);
- }
- });
- }
Comments
Post a Comment
Thank you for your comment.