This post will explain you how to Get All Sites and Sub Sites using REST Api in SharePoint Online
In order to get the list of sub sites from a site we need to call the below URL:
1 |
/_api/site/rootWeb/webinfos |
Now to get the entire site structure we will need to loop every site to see if there are any sub sites present.
Below is the code I have used.
//The First Ajax is to get the Root Site Title and the Relative URL
1 2 3 4 5 6 7 8 9 10 11 12 |
$.ajax({ url: _spPageContextInfo.siteAbsoluteUrl + "/_api/site/rootweb?$select=Title,ServerRelativeUrl", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function(rootsite) { }, error: function(rootsite) {}, async: false }); |
// The Second AJAX is to get all the sub sites under the Root Site
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$.ajax({ url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/webinfos?$select=ServerRelativeUrl,Title", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function(subsites) { $.each(subsites.d.results, function() { getSubSites(this.ServerRelativeUrl, this.Title); }); }, error: function(subsites) {}, async: false }); |
// This is a Recursive Function to loop through the sub sites and check for more sub sites
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function getSubSites(SubSiteUrl, SubSiteTitle) { console.log(SubSiteUrl); $.ajax({ url: _spPageContextInfo.siteAbsoluteUrl + SubSiteUrl + "/_api/web/webinfos?$select=ServerRelativeUrl,Title", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function(subsites) { $.each(subsites.d.results, function(index) { getSubSites(this.ServerRelativeUrl, this.Title); }); }, error: function(subsites) {}, async: false }); } |
Reference link :
http://sharepoint.stackexchange.com/questions/92467/retrieve-toplevel-sites-subsites-using-rest-api
Hello, great script, there is a way i can use a same approachs but for a site collection that have subsites with subsites?
Well this is a recursive script, so it will get you all the sites at any level, be it sitecollection -> subsite-> subsite-> subsites etc