Sharepoint - Get all Files and Folders in one call

You could try the following endpoint:

https://server/_api/Web/GetFolderByServerRelativeUrl(<folder url>)?$expand=Folders,Files

It returns files and folders beneath folder at the specified url.

JavaScript example

The following example demonstrates how to retrieve files and folder beneath 2015 folder:

var folderUrl = '/documents/2015';
var url = _spPageContextInfo.webServerRelativeUrl + "/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')?$expand=Folders,Files";

$.getJSON(url,function(data,status,xhr){

    for(var i = 0; i < data.Files.length;i++){
        console.log(data.Files[i].Name);    
    }

    for(var i = 0; i < data.Folders.length;i++){
        console.log(data.Folders[i].Name);    
    }
});

since IE9 you can also write:

$.getJSON(url,function(data,status,xhr){

    data.Files.forEach(function( file ){
        console.log( file.Name );    
    });

    data.Folders.forEach(function( folder ){
        console.log( folder.Name );    
    });
});

or if you need the individual filenames in an Array:

$.getJSON(url,function(data,status,xhr){

    var filenamesArr = data.Files.map(function( file ){
        return file.Name ;    
    });

    var foldernamesArr = data.Folders.map(function( folder ){
        return folder.Name ;    
    });
});

You can get all of the documents and folders contained directly under a given subfolder in a document library:

/_api/web/Lists/GetByTitle('DocLib')/GetItems(query=@v1)?$select=Title,File/Name&$expand=File&@v1={"ViewXml":"<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileDirRef' /><Value Type='Text'>/SubSite1/SubSite1.2/DocLib/SubFolder1/SubFolder1.3</Value></Eq></Where></Query></View>"}

If you need all of the documents and folders contained under a given subfolder recursively in a document library:

/_api/web/Lists/GetByTitle('DocLib')/GetItems(query=@v1)?$select=Title,File/Name&$expand=File&@v1={"FolderServerRelativeUrl" : "/SubSite1/SubSite1.2/DocLib/SubFolder1/SubFolder1.3", "ViewXml":"<View Scope='RecursiveAll'></View>"}";

Note, that only folder title and file name is selected in these samples. You should of course change the name of the document library and the server relative path in the query.

Tags:

Rest