SharePoint Pals
 | Sign In
Deep Dive into SharePoint 2013 and JavaScript – Part 3
by Ahamed Fazil Buhari 13 Aug 2016
Author
SharePoint Developer
Visits   
Today  :   7     Total  :    2127

Hi and welcome to our Part 3 article on – ‘Deep Dive into SharePoint 2013 and JavaScript’, this article is continuation of my previous article (Deep Dive into SharePoint 2013 and JavaScript – Part 2). Here we will look into REST (REpresentational State Transfer) which significantly expanded capabilities of SharePoint 2013.

REST

Before we start the architecture of REST there’s one tool I have to call out that you have to install. It’s called Fiddler and it’s an HTTP debugger. It allows to capture request and response traffic and analyze it and also it allows to create and submit new request quickly and easily which is very useful when we are doing REST programming. It’s a freeware and you can download it from here.

Let’s get into the main topic. REST is a mechanism of interacting with entities via URIs. Each resource we want to interact with has its own URI. For SharePoint this means interacting with lists, libraries, listItems and documents via URIs.

REST was introduced in SharePoint 2010 and enhanced in 2013. SharePoint REST interface is based on the OData spec and it doesn’t support the full spec.

All about URI (some simple examples):

 //Fetch List:
 http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')
 
 //Get all items from List
 http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')/items
 
 //Get Item with ID of 3
 http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')/items(3)
 
 //Page through items in List
 http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')/items?$top=10
 
 //Get all items from Lists where Score > 100
 http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')/items/?$filter=Score gt 100
 

URI structure in a REST call:

http://ahamed.sp.com/_api/web/lists/GetByTitle('MyList')/items?$top=10

http://ahamed.sp.com/ -> Location (Host address)

_api/ -> Service (Alias for the full name of the service endpoint, _vti_bin/client.svc)

SharePoint URLs have 256 character limit not counting the query options, just the base URL portion. So this would save some space.

After the service, we need to specify an endpoint. There are currently 5 supported endpoints in SharePoint 2013.

Endpoints:

· Site - /_api/site

· Web - /_api/web

· User Profile - /_api/SP.UserProfiles.PeopleManager

· Search - /_api/search

· Publishing - /_api/publishing

web/lists/GetByTitle('MyList')/items -> Resource path

There are hundreds of resources in SharePoint for sites, webs, lists, listitems, etc.

$top=10 -> Query Options

This is often used for filtering and limiting the fields returned and paging through the data.

· $select

· $filter

· $top/$skip

Not all OData Query operations are supported by SharePoint REST implementation.

Please refer this msdn site for OData Query operations in SharePoint 2013, https://msdn.microsoft.com/en-us/library/fp142385.aspx

HTTP Verbs:

· GET – Reading Information

· POST – Create, Update, Delete

o Verb-Tunneling – Some firewalls block all the HTTP verbs except GET and POST, it is ok for Create and Read, but there’s different approach for deletes and updates. So, here comes the use of Verb-Tunneling. It requires to submit standard POST, but we need to specify the real verb we want to use in X-Http method header.

o Body – For Create and Update we need to pass the values in the Request Body, but this is not necessary for delete.

CRUD Operation on SharePoint using REST API

Read Operation:

There are many ways to submit our request to the server, the easy way is to use JQuery Ajax function. We will now read the data using simple HTTP GET. For Ajax function, we need to give two additional things in the URL of whatever resource we are connecting to and the right HTTP header.

 $.ajax(
 {
     url: encodeURI(siteURL),
     type: "GET",
     header: {
         "accept" : "application/json;odata=verbose"
     }
 });
 
 

Results will be in JSON and the result type may differ based on the call we made. Some of the call and its result types are shown below

Call

Result Type

Accessed via

_api/web/lists

Collection

data.d.results[index]

_api/web/lists/GetByTitle(“ListName”)

Single

data.d

_api/web/lists/GetByTitle(“ListName”)/items

Collection

data.d.results[index]

_api/web/lists/GetByTitle(“ListName”)/items(id)

Single

data.d

_api/web/folders

Collection

data.d.results[index]

_api/web/GetFolderByServerRelativeUrl(‘/Lists/listname/MyFolder’)

Single

data.d

· Common Query Options

o $orderby – asc or desc

_api/web/lists/GetByTitle(“ListName”)/items/?$orderby=Title asc

o $select – specify which columns to get

_api/web/lists/GetByTitle(“ListName”)/items/?$select=Title,Body

o $filter – Allows to specify criteria to filter the items

_api/web/lists/GetByTitle(“ListName”)/items/?$filter=Price gt 1000

o $top and $skip - Used for paging through large result (it doesn’t work for list items)

_api/web/lists/?$skip=10&$top=10

To skip through the items we need to make use of Paging, which is explained below

· Paging

o List Items (List Item collections)

§ SharePoint limits the size of result set for queries

§ If we are not specifying how many items we want in each page of results, then by default it will give 100 items each time.

o List Item collection use $skiptoken and specify the ID of the last item that we do not want inside our batch

$skiptoken=Paged%3dTRUE%26p_ID%3d<# to skip>&$top=<# to retrieve>

%3d -> ‘=’ signs and %26 -> ‘&’ signs

Write Operation:

First thing is we need to use POST in http type and the second thing is we need to specify the values/properties in request body (Data that we need to write to SharePoint). And the last thing is, we need to specify the Form Digest value. We don’t always have easy access to Form Digest value using jquery.

$(“#__REQUESTDIGEST”).val() [SharePoint] – This will work if we’re submitting REST from JavaScript loaded into SharePoint page i.e. a layout page, SharePoint hosted app.

If we are calling from non-SharePoint page, then we have to get Form Digest in another way. Submit POST to,

/_api/contextinfo [Remote]

Once we have Form Digest value, we can use it to submit back to SharePoint with our write operations.

Create Operation:

Provide actual values for the item that we’re creating as a JSON object in key (‘Name of the column’) – value (‘value for that column’) pair.

· Column Names

 var values  = {
 “Col1”	: ”Data1”,
 “Col2” : “Data2”,
 “__metadata” : {“type” : “SP.Data.” + <<name of the list>> + “ListItem”}
 }
 

Along with these, we need to supply another key value pair, i.e. “__metadata“ – It tells the SharePoint, what kind of item we’re creating.

Once we create this JSON object, we need to convert it into string and passed as request body.

var itemData = JSON.stringify(values);

· Request Headers

We need to have request headers, in the below context you will find the headers object for code originating from SharePoint.

 var header = {
 	“accept” : “application/json;odata=verbose”,
 	“content-length” : itemData.length,
 	“X-RequestDigest” : $(“#__REQUESTDIGEST”).val()
 }
 

Finally we pack this all and send to SharePoint, using JQuery ajax function.

 $.ajax({
 	url: encodeURI(baseurl),
 	type: “POST”,
 	contentType: “application/json;odata=verbose”,
 	data: itemData,
 	headers: headers
 });
 

This is same as Reading data except we have two properties data and type: “POST”.

Update Operation:

Updating items in SharePoint using REST is a bit different. We can use two ways here, either Http PUT or Http POST

· Http PUT:

Here we need to specify all the fields or else it will take its default value. So more common people use POST.

· Http POST:

o X-Http-Method and If-Match

In this we need to make use of Verb Tunneling which we talked about earlier in this article, and pass the value as PATCH. We do this by setting X-Http-Method header to PATCH, along with these we need to specify the fields which we need to update. The last thing is we need to tell which version we need to update, we do this with If-Match header and it is called as eTag, it is not the SharePoint version, it will work regardless of whether or not we’ve enabled version in our list or library.

When we submit a request to update an item in SharePoint, we pass the eTag that we received when we retrieved the item in the If-Match header. If no one updated the item that we retrieved, which would have caused the eTag version on the server to change, then our update will go through. If the eTag value on the server is different from the eTag that we pass, then our update will fail.

If we want to update the item on the server regardless of its eTag value or its version then we need to specify * in our If-Match header. It will match any version on the server and update it.

Delete Operation:

Delete is similar to an update. Here, we still need POST, X-Http-Method header to DELETE, IF-Match rules what we already seen in Update Operation, Content-Length value to 0 but we do not set anything in the body.

Complete basic operations SP 2013 using REST has given in the official MSDN site -> click here

Happy Coding

Ahamed

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation