SharePoint Online: Add Content Type to List using Rest API

Introduction

Here we will discuss how we can add a content type to list using Rest API in SharePoint online Office 365. The same rest API code will also work in SharePoint 2013 as well as SharePoint 2016.

In this example let us take a button and on click on the button, we will add the reservation content type to a custom list which is there in the site. Both the HTML code and the rest API code let us put inside a script editor web part which is there inside a web part page.

 

HTML Code  

<div>
<input type="button" id="btnSubmit" value="Add Content Type to List" />
</div>
<div id="divResults"></div>

 

Rest API Code

Here if you will look at the code, we are adding a content type id like below:

 "contentTypeId": "0x0102004F51EFDEA49C49668EF9C6744C8CF87D" 

In this particular example, the ID is the id of a reservation content type. To get any content type id, you can go to the site settings -> then Site Content Type. Then you can click on any of the content type and from the browser, you can get the content type id. You will see like below:

?ctype=0x0102004F51EFDEA49C49668EF9C6744C8CF87D

Below is the full rest API code.

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 
<script>
$(function () {
bindButtonClick();
});
 
function bindButtonClick() {
$("#btnSubmit").on("click", function  () {
addContentType();
});
}
function addContentType() {
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/ContentTypes/AddAvailableContentType";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({            
            "contentTypeId": "0x0102004F51EFDEA49C49668EF9C6744C8CF87D"           
        }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Content Type Added Successfully to List !!!");
}
function onQueryFailed() {
alert('Error!');
}
</script>

Once you Save the page, you can see a button will appear and on button click, it will add the particular content type to the list which looks like below:

 

Now if you will open the list, you can see the content type like below:

 

 

 

References

You can also read some useful articles below:

 

Conclusion

Here we have discussed how we can add an existing content type to a custom list in SharePoint online using javascript object model (jsom).