SharePoint 2013 REST API Reference

SharePoint 2013 introduces a Representational State Transfer (REST) interface that opens the SharePoint 2013 development platform to standard Web technologies and languages. These comparable to the existing SharePoint client object models. Now, developers can interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their apps for SharePoint, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax. Reference
Sample REST endpoint:
http://server/site/_api/lists/getbytitle('listname')
the above api gets the List ‘listname’, by the method ‘getbytitle’.    

Before it can do anything with SharePoint, your remote Web or mobile application must obtain authorized access.

One of the approach would be using Oauth. The MSDN Library article, “Authentication Code OAuth flow for apps in SharePoint 2013” (http://msdn.microsoft.com/en-us/library/office/jj687470(v=office.15).aspx) OAuth flow for apps that request permission to access SharePoint resources on the fly, and how to use the OAuthAuthorize.aspx page and the SharePoint redirect URI. Once you have a token, you need to pass it with each REST request. You do this by adding an Authorization header that passes the access token as its value, preceded by “Bearer”:

Authorization: Bearer access_token

This example, which retrieves all of the lists from a SharePoint site, shows you what a basic REST request that passes an OAuth token looks like:

C#

HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("http:// <http:///> <site url>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization","Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
Stream dataStream = null;
StreamReader reader = null;
string responseFromServer = null;
dataStream = endpointResponse.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd(); 

Apex:

string EndPointUrl='http:// <http:///> <site url>/_api/web/lists';
HttpRequest req = new HttpRequest();
req.setEndpoint(EndPointUrl);
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' +accessToken);
req.setHeader('Accept','application/json;odata=verbose');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug('*****Response*****'+res.getBody());

Constructing RESTful URLs:

The SharePoint REST service is implemented in a client.svc file in the virtual folder /_vti_bin on the SharePoint Web site, but SharePoint 2013 supports the abbreviation “_api” as a substitute for “_vti_bin/client.svc.” This is the base URL for every endpoint:

http://<domain>/<site url>/_api/

The service-relative URLs of specific endpoints are appended to this base; for example, you can retrieve the lists from a SharePoint site with this URL:

http://<domain>/<site url>/_api/web/lists

You can get a reference to a particular list by specifying its ID or, as in the following example, by its title:

_api/web/lists/getByTitle('samplelist')

Every major class of the SharePoint content object model is available, including site collection, Web sites, lists, folders, fields and list items. You can get information about users through the SP.User, SP.UserCollection, SP.Group and SP.GroupCollection classes.

 

By default, the data is returned as XML in AtomPub format as extended by the OData format, but you can retrieve the data in JSON format by adding the following accept header to the HTTP request:

accept: application/json;odata=verbose

Some of the important REST API URLs:

Below are some of the important REST urls, for all of the below Base URL will be:

Base URL: http://<domain>/<site url>/
ex: https://mysite.sharepoint.com/

We can test these urls with Google Postman which is an add-on for Google Chrome Browser.


For example on how we can test using Postman please find the screenshot of chrome below (click to enlarge).


Lists and list items REST endpoints

Refer below url for all the available REST APIs for List and List Item operations.


URL
Type
Description
_api/web/lists
GET
Retrieves all the Lists in the site.
_api/web/lists(guid'<list id>')
GET
Retrieves a List by List GUID.
_api/web/lists/getByTitle('Announcements')/fields
GET
Retrieves all the columns (fields) in the Announcements list.
_api/web/lists/getByTitle('Employee')/items
GET
Retrieves all the items in ‘Employee’ List.
_api/web/lists
POST
Create a List.

{

 '_metadata':{'type':SP.List},

  'AllowContentTypes': true,

  'BaseTemplate': 100,

  'ContentTypesEnabled': true,

  'Description': 'My list description',

  'Title': 'MyListTitle'

}

Here BaseTemplate refers to the type of the list you want to create.
100: GenericList
101: DocumentLibrary
104: Announcements
Refer below link for different possible values:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx
_api/web/lists/GetByTitle(‘Test')/items(item id)
GET
Retrieves List item with specified ID.
_api/web/lists/GetByTitle(‘Test')/items(item id)
POST
Delete a List Item.
{

 "IF-MATCH”: "*",

   "X-HTTP-Method":"DELETE"

}
_api/web/lists/GetByTitle(‘Test’)/fields
POST
Create a new column in the List.

{

'__metadata':

 {

 'type': 'SP.FieldText'

 },

 'FieldTypeKind': 2,

 'Title': ‘columnName’,

 'MaxLength': '22'

}

Here FieldTypeKind is and integer that specifies the type of the column being created.
1: Integer
2: Text
4: DateTime
Refer below link for different possible values:

/_api/web/lists(guid'list GUID')/getitems

POST
Returns a collection of items from the list based on the specified query

body: "{

 'query' :

 {

  '__metadata':

  { 'type': 'SP.CamlQuery'

  },

  "ViewXml":    "<View><Query><Where><Contains><FieldRef Name='Status'/><Value Type='CHOICE'>in progress</Value></Contains></Where></Query></View>"

 }

}"


_api/web/lists/getByTitle('Employee')/items
POST
 Create a list item.

body: "

{

'__metadata': {

 'type': 'SP.Data.EmployeeItem'

 },

 'Title': ‘John Smith',

 'Department': ‘IT’,

 'StartDate':'2014-01- 29T08:00:00Z',

 'EID':7893

 }

}"


_api/web/lists/getByTitle('Employee')/items(item id)
POST
Update a List item

body: "{

 '__metadata': {

 'type': 'SP.Data. EmployeeItem'

},

'Title': ‘George Smith',

 'Department': ‘IT’,

 'StartDate':'2014-01- 29T08:00:00Z',

 'EID':7893

}"


_api/web/lists/getByTitle('Employee')
POST
Delete a List.

headers: {

    "IF-MATCH”: "*",

    "X-HTTP-Method": "DELETE"

  }



 

Files and folders REST APIs

Refer below url for all the available REST APIs for List and List Item operations.

URL
Type
Description
_api/web/getfilebyserverrelativeurl('/Shared Documents/filename.docx')
 
GET
Get a file metadata; gets the metadata of file ‘filename.docx’
_api/web/getfilebyserverrelativeurl('/Shared Documents/filename.docx')
/$value
 
GET
Get file contents (media resource) by file name
_api/web/getfolderbyserverrelativeurl('/Shared 
Documents')/files add(overwrite=true,url='filename.txt')
 
POST
Add a new File.
body: "Contents of the file go here"
The Stream contents of the
 file. Pass the content parameter in the
 request body. The maximum
size of a binary file that you can add by using the REST
 API is 2 GB.
_api/web/getfolderbyserverrelativeurl('/Shared 
Documents')
POST
Delete a document library.
headers: { "X-HTTP-Method":"DELETE" }
 
_api/web/getfilebyserverrelativeurl('/Shared 
Documents/filename.docx')

POST

Delete a file.
headers: { "X-HTTP-Method":"DELETE" }

_api/web/lists
 
POST

Create a document Library.
body: "{ '__metadata': { 
'type': 'SP.List' }, 
'AllowContentTypes': true,
 'BaseTemplate': 101,
    'ContentTypesEnabled': 
true, 'Description': 'My 
library description', 
'Title': ‘library title' }"
 

Site and User REST APIs

Refer below url for all the available REST APIs for List and List Item operations.

http://go.microsoft.com/fwlink/?LinkId=331059

URL
Type
Description
_api/web/title
GET
Returns the title of the current site.
_api/web/siteusers
GET
Retrieves all the users in the site.
_api/web/siteusers(@v)?@v= i%3A0%23.f%7Cmembership%7Cuser%40domain.onmicrosoft.com
'
GET
Get a user by username.
Username is decoded here. (i:0#.f|membership|user@domain.onmicrosoft.com)
_api/web/sitegroups
GET
Retrieves all the user groups in the site.
_api/web/sitegroups(3)/users
GET
Retrieves all the users in group 3.

Advanced Operations

1.              Filtering, Selecting and Sorting

The SharePoint 2013 REST interface supports operations for sorting, filtering and ordering the data that it returns.

You can use OData system query options to control what data is returned and how it’s sorted. Below table shows the supported options.

 

Option
Purpose
$select
Specifies which fields are included in the returned data.
$filter
Specifies which members of a collection, such as the items in a list, are returned.
$expand
Specifies which projected fields from a joined list are returned.
$top
Returns only the first n items of a collection or list.
$skip
Skips the first n items of a collection or list and returns the rest.
$orderby
Specifies the field that’s used to sort the data before it’s returned.

 

 

Examples:

·         To return the Name, Dept and Date of Birth from a list called Employee, we can use the following:

 

       _api/web/lists/getByTitle('Employee')/items?$select=Name,Dept,DOB

If the $select option isn’t used, all fields are returned except fields that would be resource-intensive for the server to return. If you need these fields, you need to use the $select option and specify them by name. To get all fields, use $select=‘*’.

 

·         To get all the employees of department I.T., use:

 

        _api/web/lists/getByTitle('Employee')/items?$filter=Dept eq ‘IT’

·         To sort the employees  by name in descending order, use:

 

       _api/web/lists/getByTitle('Employee')/items?$orderby=Name dsc

Use “asc” in place of “dsc” to specify ascending order. To sort by multiple fields, specify a comma-separated list of fields.

 

·         You can conjoin multiple options using the “&” operator. To get only the Names of the first two employees of I.T., use:

 

       _api/web/lists/getByTitle(
 'Employee')/items?$select=Name&$filter=Dept eq ‘IT’&$top=2

·         The service will completely resolve each option before it applies the next one. So each option only applies to the data set that’s produced by the options to its left in the URL. Thus, the order in which you apply the options matters. For example, the following URL returns items 3-10:

 

        _api/web/lists/getByTitle(‘Employee’)/items?$top=10&$skip=2

·         But reversing the two options returns items 3-12:

 

       _api/web/lists/getByTitle(‘Employee’)/items?$skip=2&$top=10

·         You can get the bottom n items by using a descending $orderby and a $top option (in that order). The following URL gets the bottom two items:

 

        _api/web/lists/getByTitle(‘Employee’)/items?$orderby=ID desc&$top=2

·         When a SharePoint list has a lookup field to another list, this effectively serves as a join of the two lists. You can use the $expand option to return projected fields from the joined list. For example, if the Employee list has a Dept field that looks up to the Name field of a Departments list, you can return those names with this URL:

 

       _api/web/lists/getByTitle(
  ‘Employee’)/items?$select=Name,Dept/Name&$expand=Dept

Notice that you reference the column in the foreign list by using the syntax lookup_column_display_name/foreign_column_name, not foreign_list_name/foreign_column_name. It’s also important to note that you can’t select a lookup field name without also expanding it.


The figure below shows the supported OData query options.

 

 

2.              Working with Files and Folders

Adding file to document library and updating the metadata columns:

Above operation needs to be split up in to two phases since adding a file and updating the metadata columns in a single call is not possible.

 

Add file to document library.

The best way to reach a document library is by taking advantage of the GetFolderByServerRelativeUrl method that’s available at /_api/web. When you add a file to a document library, you send the contents of your file in the request body, and you pass the name of the file in the URL:

 


http://<site url>/_api/web/GetFolderByServerRelativeUrl('/My Library')/Files/add(url='Document.docx',overwrite=true)

Pass the file content as byte stream to the http call.

 

Get the list item associated with the file.

The response from above call that uploads the document will be a SP.File object representing the file that was just created. This object will have a deferred property called ListItemAllFields, which you can use to get the URL needed to make a call to get the list item associated with the file.

Sample Response:

 

 

/_api/Web/GetFileByServerRelativeUrl('/library name/file name.docx')/ListItemAllFields

From the above call we will get the list item as response.

Sample response:

 

 

Update the list item fields.

Once you have the list item you can then make a call to set the field value.

Above response will have __metadata property called uri, which we can use for metadata updating.

 

       url: ‘https://<site name>/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Items(5)
        type: "POST",
        data: "__metadata": { type: "sP.Data.SalesForce_x0020_FilesItem " },
            AccountId: ‘Ac00001’,
            Name: ‘John Smith’
        })
headers: {
            Accept: "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "IF-MATCH":’1’,
            "X-Http-Method": "MERGE"
        }

Thank you for spending your precious time with my blog.


Comments

  1. I am creating a file on sharepoint through salesforce rest api.
    File is created succesffuly in sharepoint.But when try to open it is not opening.

    ReplyDelete
  2. How to get the access token?Can anyone suggest URL for that.

    ReplyDelete
    Replies
    1. Yes please, the url has expired and I'm having difficulty fetching the access token.

      Delete
  3. how to download sharepoint file through rest api?

    ReplyDelete
  4. how to create folders in sahrepoint by using REST API?

    ReplyDelete

Post a Comment

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control