14

I want to get all the files and folders contained inside a SharePoint folder in one rest API call.

We have the below API to get all the folders inside a folder

<YouDomainServer>/_api/Web/GetFolderByServerRelativeUrl(<relativepath>)/Folders

We have the below api to get all the files inside a folder

<YouDomainServer>/_api/Web/GetFolderByServerRelativeUrl(<relativepath>)/Files

Can I get the result of both these calls in a single API call??

Arsalan Adam Khatri
  • 14,531
  • 3
  • 36
  • 59
jkr
  • 403
  • 1
  • 6
  • 19

2 Answers2

19

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 ;    
    });
});
Danny '365CSI' Engelman
  • 21,176
  • 7
  • 35
  • 79
Vadim Gremyachev
  • 42,498
  • 3
  • 86
  • 167
6

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('DocLibrary')/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.

Spinner
  • 125
  • 1
  • 8
pholpar
  • 3,190
  • 1
  • 15
  • 14