SharePoint Online Office 365 : Delete SharePoint Site using Rest API
Introduction:
Here we will discuss how we can delete a SharePoint site using Rest API in SharePoint Online Office 365. The same code will also work in SharePoint 2013 and SharePoint 2016. You can also check my previous article on Create SharePoint Site using Rest API in SharePoint Online Office 365.
Here in this example we are going to take a textbox and a button. User can put the site title in the textbox and can click on the button to delete the site. The html code looks like below and the div with id divResults will display the successful message when site will get deleted successfully.
HTML Code:
<div id="DeleteSite">
<div>
<strong>Enter Name of Site to Delete:</strong>
<br />
<input type="text" id="txtSiteTitle" />
</div>
<br />
<input type="button" id="btnSubmit" value="Delete Site" />
</div>
<div id="divResults"></div>
Rest API Code:
Below is the Rest API code, here we have taken the site from the textbox. Let us added the full html and rest api code inside a script editor web part. You can also use content editor web part. For this example let us put inside a script editor web part in a web part page.
<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 () {
deleteSite();
});
}
function deleteSite() {
var siteTitle = $("#txtSiteTitle").val();
var siteTitleNoSpaces = siteTitle.replace(/\s/g, "");
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/" + siteTitleNoSpaces + "/_api/web";
$.ajax({
url: fullUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"IF-MATCH": "*"
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Site deleted successfully !");
}
function onQueryFailed(sender, args) {
alert('Error!');
}
</script>
Once you save the page, the form will appear like below, where use can put the title and click on the Delete Site button. If the site will get deleted successfully, it will show successful message like below:
https://www.enjoysharepoint.com/wp-content/uploads/2018/07/rest-api-delete-site-sharepoint-2013.png
Now if you will check the Site Contents page, you can see the site will not be there.
References:
Conclusion:
Here we have checked how we can delete site using rest api in SharePoint Online.