VilleLipponen
VilleLipponen

Reputation: 656

Access files in Sharepoint 2010 using REST API

I know very little about Sharepoint. We have an SP site: http://host/sites/project/subproject/LIBRARY%20Name/Forms/AllItems.aspx

Navigating to this in the browser shows me a list of files. I want to use SPs REST API to programatically access these files.

I've learned that the REST API is accessed through the http://host/_vti_bin/ListData.svc URL. In the browser this returns XML that contains entries for Services, Documents, Images, etc.

To access files i tried the following URLs:

   http://host/_vti_bin/ListData.svc/Documents
   http://host/_vti_bin/ListData.svc/Documents('LIBRARY%20Name')
   http://host/_vti_bin/ListData.svc/Documents?$select=NAME('LIBRARY%20Name')

, and many other variations.

My question is, given the URL of our site, what would the REST API service URL look like?

Thanks

Upvotes: 1

Views: 3513

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

Apart from SharePoint 2013 and later versions, REST API for SharePoint 2010 supports a relatively restrictive set of resources, in particular File resource is not supported.

Having said that you could consider the following approach for downloading a file.

In order to download a particular file from a library, lets assume list item id is provided in addition to web url and library name.

First GET request returns so called document item (Microsoft.SharePoint.DataService.DocumentsItem type) using the following endpoint:

https://<weburl>/_vti_bin/listdata.svc/<listname>(<itemid>) 

Once document item is retrieved, file url could be extracted from Path and Name properties (see below example), and finally downloaded via HTTP GET

C# example

var webUrl = "https://intranet.contoso.com/";
var listName = "Documents";  //<-list name goes here
var itemId = 1; //<-list item id goes here
using (var client = new WebClient())
{
    client.BaseAddress = webUrl;
    client.Credentials = credentials;
    client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
    //client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    var url = String.Format("_vti_bin/listdata.svc/{0}({1})",listName,itemId);
    var content = client.DownloadString(url);
    var json = JObject.Parse(content);
    //extract file url
    var fileUrl = (string)json["d"]["Path"] +  "/" + (string)json["d"]["Name"];
    Console.WriteLine(fileUrl);
    //download a file
    var fileName = Path.GetFileName(fileUrl);
    client.DownloadFile(fileUrl,fileName);
}

Upvotes: 3

Related Questions