Ram Prasad
 

REST API Endpoint and JSOM Code to get the list of sub sites for the current user

Aug, 23 2016
 
1 min/s
 
 

While working with any SharePoint site, there might be a need to display the list of sub sites to which the current user has access, using JSOM or REST APIs. One might end up writing the below code for getting the list of sub sites for the current user.

JSOM

	var ctx = SP.ClientContext.get_current();
	var parentWeb = ctx.get_web();
        var subWebs = parentWeb.get_webs();

REST API ENDPOINT

http://<site url>/_api/web/webs

The above code works perfectly when all the sub sites do not have unique permissions and are inheriting permissions from its parent. But if any of the sub sites are having unique permissions and if the current user do not have access to one of these sub sites, the above code will throw an error (shown below).

Access denied. You do not have permission to perform this action or access this resource
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

To get the list of sub sites available for the current user, one has to use the following JSOM or REST API code.

JSOM

Use the getSubwebsForCurrentUser method of SP.Web class to get the collection of child sites for the current user.

	var ctx = SP.ClientContext.get_current();
	var parentWeb = ctx.get_web();
        var subWebs = parentWeb.getSubwebsForCurrentUser(null);

Reference : MSDN

This works for both SharePoint Server 2013 & SharePoint online.

REST API ENDPOINT

http://<site url>/_api/web/getsubwebsfilteredforcurrentuser(nwebtemplatefilter=-1,nconfigurationfilter=0)

Reference: MSDN

At the time of writing this article, this endpoint is available only for SharePoint Online.

With the above snippets, we can get the list of subsites for the current user in any scenario i.e., sub sites with unique permissions and ones which are inheriting permissions from parent.