Skip to content

Latest commit

 

History

History
356 lines (278 loc) · 13.1 KB

working-with-folders-and-files-with-rest.md

File metadata and controls

356 lines (278 loc) · 13.1 KB
titledescriptionms.datems.localizationpriorityms.service
Working with folders and files with REST
Perform basic create, read, update, and delete (CRUD) operations on folders and files with the SharePoint REST interface.
01/12/2023
high
sharepoint

Working with folders and files with REST

Note

The examples on this page do not support the % and # characters. Support % and # in files and folders with ResourcePath API

Tip

The SharePoint Online (and on-premises SharePoint 2016 and later) REST service supports combining multiple requests into a single call to the service by using the OData $batch query option. For details and links to code samples, see Make batch requests with the REST APIs.

Working with folders by using REST

You can retrieve a folder inside a document library when you know its URL. For example, you can retrieve the root folder of your Shared Documents library by using the endpoint in the following example.

GEThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Shared Documents')Authorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

The following XML shows an example of folder properties that are returned when you request the XML content type.

<contenttype="application/xml"> <m:properties> <d:ItemCountm:type="Edm.Int32">0</d:ItemCount> <d:Name>Shared Documents</d:Name> <d:ServerRelativeUrl>/Shared Documents</d:ServerRelativeUrl> <d:WelcomePage/> </m:properties> </content>

The following example shows how to create a folder.

POSThttps://{site_url}/_api/web/foldersAuthorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"Content-Type: "application/json"Content-Length: {length of request body as integer}X-RequestDigest: "{form_digest_value}" { "__metadata": { "type": "SP.Folder" }, "ServerRelativeUrl": "/document library relative url/folder name" }

The following example shows how to rename a folder by using the MERGE method.

First, obtain the folder's OData type with a GET request.

GEThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/ListItemAllFieldsAuthorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

From the result, obtain the odata.type value, such as SP.Data.Shared_x0020_DocumentsItem (the value may be different depending on your library configuration). Then submit a MERGE request:

POSThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/ListItemAllFieldsAuthorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"Content-Type: "application/json"Content-Length: {length of request body as integer}If-Match: "{etag or *}"X-HTTP-Method: "MERGE"X-RequestDigest: "{form_digest_value}" { "__metadata": { "type": "{odata.type from previous call}" }, "Title": "New name", "FileLeafRef": "New name" }

The following example shows how to delete a folder.

POSThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')Authorization: "Bearer " + accessTokenIf-Match: "{etag or *}"X-HTTP-Method: "DELETE"X-RequestDigest: "{form_digest_value}"

Working with files by using REST

The following example shows how to retrieve all of the files in a folder.

GEThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/Filesmethod: GETAuthorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

The following example shows how to retrieve a specific file.

GEThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/Files('{file_name}')/$valueAuthorization: "Bearer " + accessToken

You can also retrieve a file when you know its URL, as in the following example.

GEThttps://{site_url}/_api/web/GetFileByServerRelativeUrl('/Folder Name/{file_name}')/$valueAuthorization: "Bearer " + accessToken

The following code sample shows how to retrieve a file when you know its URL by using the REST endpoint above and C#.

/// <summary>/// Download File Via Rest API/// </summary>/// <param name="webUrl">https://xxxxx/sites/DevSite</param>/// <param name="credentials"></param>/// <param name="documentLibName">MyDocumentLibrary</param>/// <param name="fileName">test.docx</param>/// <param name="path">C:\\</param>publicstaticvoidDownloadFileViaRestAPI(stringwebUrl,ICredentialscredentials,stringdocumentLibName,stringfileName,stringpath){webUrl=webUrl.EndsWith("/")?webUrl.Substring(0,webUrl.Length-1):webUrl;stringwebRelativeUrl=null;if(webUrl.Split('/').Length>3){webRelativeUrl="/"+webUrl.Split(newchar[]{'/'},4)[3];}else{webRelativeUrl="";}using(WebClientclient=newWebClient()){client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED","f");client.Credentials=credentials;UriendpointUri=newUri(webUrl+"/_api/web/GetFileByServerRelativeUrl('"+webRelativeUrl+"/"+documentLibName+"/"+fileName+"')/$value");byte[]data=client.DownloadData(endpointUri);FileStreamoutputStream=newFileStream(path+fileName,FileMode.OpenOrCreate|FileMode.Append,FileAccess.Write,FileShare.None);outputStream.Write(data,0,data.Length);outputStream.Flush(true);outputStream.Close();}}staticvoidMain(string[]args){stringsiteURL="https://xxxxx/sites/DevSite";//set credential of SharePoint onlineSecureStringsecureString=newSecureString();foreach(charcin"Password".ToCharArray()){secureString.AppendChar(c);}ICredentialscredentials=newSharePointOnlineCredentials("xxxxxx.onmicrosoft.com",secureString);//set credential of SharePoint 2013(On-Premises)//string userName = "Administrator";//string password = "xxxxxxx";//string domain = "CONTOSO";//ICredentials credentials = new NetworkCredential(userName, password, domain);DownloadFileViaRestAPI(siteURL,credentials,"MyDocumentLib","test.docx","c:\\");Console.WriteLine("success");Console.ReadLine();}

The following example shows how to create a file and add it to a folder.

POSThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/Files/add(url='a.txt',overwrite=true)Authorization: "Bearer " + accessTokenContent-Length: {length of request body as integer}X-RequestDigest: "{form_digest_value}""Contents of file"

The following example shows how to update a file by using the PUT method.

Note

PUT is the only method that you can use to update a file. The MERGE method is not allowed.

POSThttps://{site_url}/_api/web/GetFileByServerRelativeUrl('/Folder Name/{file_name}')/$valueAuthorization: "Bearer " + accessTokenContent-Length: {length of request body as integer}X-HTTP-Method: "PUT"X-RequestDigest: "{form_digest_value}""Contents of file"

If you want to update a file's metadata, you have to construct an endpoint that reaches the file as a list item. You can do this because each folder is also a list, and each file is also a list item. Construct an endpoint that looks like this: https://{site_url}/_api/web/lists/getbytitle('Documents')/items({item_id}). For information about how to update a list item's metadata, see Working with lists and list items with REST.

You may want to check out a file to make sure that no one changes it before you update it. After your update, you should check the file back in so that others can work with it.

The following example shows how to check out a file.

POSThttps://{site_url}/_api/web/GetFileByServerRelativeUrl('/Folder Name/{file_name}')/CheckOut(),Authorization: "Bearer " + accessTokenX-RequestDigest: "{form_digest_value}"

The following example shows how to check in a file.

POSThttps://{site_url}/_api/web/GetFileByServerRelativeUrl('/Folder Name/{file_name}')/CheckIn(comment='Comment',checkintype=0)Authorization: "Bearer " + accessTokenX-RequestDigest: "{form_digest_value}"

The following example shows how to delete a file.

POSThttps://{site_url}/_api/web/GetFileByServerRelativeUrl('/Folder Name/{file_name}')Authorization: "Bearer " + accessTokenIf-Match: "{etag or *}"X-HTTP-Method: "DELETE"X-RequestDigest: "{form_digest_value}"

Working with large files by using REST

When you need to upload a binary file that is larger than 1.5 megabytes (MB), the REST interface is your only option. For a code example that shows you how to upload a binary file that is smaller than 1.5 MB by using the SharePoint JavaScript object model, see Complete basic operations using JavaScript library code in SharePoint. The maximum size of a binary file that you can create with REST is 2 gigabytes (GB).

The following example shows how to create a large binary file.

Warning

This approach works only with Internet Explorer 10 and the latest versions of other browsers.

POSThttps://{site_url}/_api/web/GetFolderByServerRelativeUrl('Folder Name')/Files/Add(url='{file_name}', overwrite=true)Authorization: "Bearer " + accessTokenContent-Length: {length of request body as integer}X-RequestDigest: "{form_digest_value}"Contents of binary file

The following code sample shows how to create a file by using this REST endpoint and the JSOM cross-domain library.

functionuploadFileBinary(){XDomainTestHelper.clearLog();varrequestExecutor;if(document.getElementById("TxtViaUrl").value.length>0){requestExecutor=newSP.RequestExecutor(document.getElementById("TxtWebUrl").value,document.getElementById("TxtViaUrl").value);}else{requestExecutor=newSP.RequestExecutor(document.getElementById("TxtWebUrl").value);}varbody="";for(vari=0;i<1000;i++){varch=i%256;body=body+String.fromCharCode(ch);}varinfo={url: "_api/web/lists/getByTitle('Shared Documents')/RootFolder/Files/Add(url='a.dat', overwrite=true)",method: "POST",binaryStringRequestBody: true,body: body,success: success,error: fail,state: "Update"};requestExecutor.executeAsync(info);}

Working with files attached to list items by using REST

The following example shows how to retrieve all of the files that are attached to a list item.

GEThttps://{site_url}/_api/web/lists/getbytitle('{list_title}')/items({item_id})/AttachmentFiles/Authorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

The following example shows how to retrieve a file that is attached to a list item.

GEThttps://{site_url}/_api/web/lists/getbytitle('{list_title}')/items({item_id})/AttachmentFiles('{file_name}')/$valueAuthorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

The following example shows how to create a file attachment to a list item.

POSThttps://{site_url}/_api/web/lists/getbytitle('{list_title}')/items({item_id})/AttachmentFiles/ add(FileName='{file_name}')Authorization: "Bearer " + accessTokenContent-Length: {length of request body as integer}X-RequestDigest: "{form_digest_value}""Contents of file"

The following example shows how to update a file attachment to a list item by using the PUT method.

Note

PUT is the only method that you can use to update a file. The MERGE method is not allowed.

POSThttps://{site_url}/_api/web/lists/getbytitle('{list_title}')/items({item_id})/AttachmentFiles('{file_name}')/$valueAuthorization: "Bearer " + accessTokenContent-Length: {length of request body as integer}X-HTTP-Method: "PUT"X-RequestDigest: "{form_digest_value}""Contents of file"

The following example shows how to delete a file that is attached to a list item.

DELETEhttps://{site_url}/_api/web/lists/getbytitle('{list_title}')/items({item_id})/AttachmentFiles('{file_name}')Authorization: "Bearer " + accessTokenAccept: "application/json;odata=verbose"

See also

close