10

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??

17

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 ;    
    });
});
5

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.

  • Thank you for the response phoplar. The first answer works well inmy case – jkr Apr 15 '15 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.