CRUD Operations using REST

Before looking at CRUD Operations, let us understand the concepts and variables used in it.

_spPageContextInfo :

It is a context variable rendered for each sharepoint page. Properties of _spPageContextInfo are:

Properties Values
webServerRelativeUrl “\sites\SharePointConnect”
webAbsoluteUrl “https:\wordpress.com.com\sites\SharePointConnect”
siteAbsoluteUrl “https:\wordpress.com\sites\SharePointConnect”
serverRequestPath “\sites\SharePointConnect\SitePages\Home.aspx”
layoutsUrl “_layouts\15”
webTitle “SharePointConnect”
webTemplate “1”
tenantAppVersion “3289089430”
isAppWeb false
webLogoUrl “https:\wordpress.com\sites\SharePointConnect\SiteAssets\logo.JPG”,
webLanguage 1033
currentLanguage 1033
currentUICultureName “en-US”
currentCultureName “en-US”
clientServerTimeDelta new Date(“2016-06-10T05:08:10.2860519Z”) – new Date()
siteClientTag “0$$15.0.4285.1000″
crossDomainPhotosEnabled false
webUIVersion 5
webPermMasks {High:2147484897,Low:3294958795}
pageListId ”{e40453e1-7c5c-4c8e-87dc-061b48931fea}”
pageItemId 1
pagePersonalizationScope 1
userId 6789
systemUserKey ”i:0\u0040.w|s-1-5-21-1743670581-294256949-3035048756-78901787″
alertsEnabled true
siteServerRelativeUrl “\sites\SharePointConnect”
allowSilverlightPrompt ‘True’

HTTP Methods:

METHOD USAGE
GET Retrieve the resource or retrieve data from Server
POST Creates the resource or submit the data to the server
DELETE Deletes the resource
MERGE Updates only the fields that are specified and maintains the same value(i.e. previous values) for all other fields
PUT Updates all the fields even if not specified. For unspecified fields, it uses default values.

Headers:

Accept: Used to specify the language that the client(browser) will accept
Content-type: Used to specify the language in which the data exists or the language in which the client will send when it is requested.
X-RequestDigest: Used to hold the form digest(request digest) value

Request Digest Value:
When a valid request is sent to the server and the same request is then sent multiple times fraudulently, replay attack occurs. Replay attacks can be better understood in case of transferring money. Imagine what happens if the same money transfer is sent multiple times.This can be prevented using request digest value which identifies the fake requests. For SharePoint-Hosted app, the request digest value lies in _REQUESTDIGEST object of page and can be retrieved in jquery as:

 $(“#__REQUESTDIGEST”).val()

This value should be used in create, update and delete operations to avoid replay attack.

Finding the List Item Type:

For create and update operations, list item type should be included. List item type is a string created by SharePoint when a list is created. We can easily determine the list item type using the format: SP.Data.ListNameListItem . If list name is EmployeeDetails then List Item Type will be SP.Data.EmployeeDetailsListItem. This does not work all the time because if List Name starts in small case, it capitalizes the first letter of the list name. so it is better to always capitalize the first letter of the list name and then pass the rest of the characters in list name using slice.

Slice is a method which extracts the part of a string. Its syntax is slice(start,end) where start parameter is required and end parameter is optional. If end is omitted, it extracts till the end.

“SP.Data.” + name.charAt(0).toUpperCase() + name.slice(1) + “ListItem”;

NOTE: This function does not work when the list name has special characters or spaces in between. In such cases, you can use the below function to find out the list item type.

function getItemTypeForListName(listTitle)
{
return executeJson({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName",
method: 'GET'
}).then(function(data){
return data.d.ListItemEntityTypeFullName;
});
}
getItemTypeForListName(listTitle)
.done(function(name){
alert(name);
})
.fail(function(error){
console.log(JSON.stringify(error));
});
function executeJson(options)
{
var headers = options.headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: options.method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(options.method == "POST") {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}

Consider a SharePoint List ” Employee Details” for performing CRUD Operations using REST.

Employee Details

Entity Tag(E-Tag):

E-Tag is used for Cache validation and conditional requests. When the client sends the request, the server responds with E-Tag which is stored in browser cache. If the same request is sent again, the browser validates the request with cache in “If- None-Match” header to the server. If E-Tag of the server and the browser matches, then server returns “304 Not modified status code” saying the browser to use the browser cache. If E-Tag does not match, server will respond to the request with new E-Tag.

Similar to If-None- Match header, “If-Match” header can be used for Conditional GET requests. If the E-Tag matches, 200(OK) is returned else 412 will be returned saying precondition failed.

The meaning of “If-Match: *” is that the method should be performed if the representation selected by the origin server exists, and must not be performed if the representation does not exist.

Read Operation:

<script src="/SiteAssets/jquery.min.js"></script>
<script>
$(document).ready(function()
{
read();
});
function read()
{
var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee Details')/items";
$.ajax({
  url: resturl,
  method: "GET",
  headers: { 
	"Accept": "application/json; odata=verbose"
	 },
	 success: function (data) {
	 var lnt = data.d.results.length;
	 for(var i=0; i<lnt; i++ )
	 {
	  var title = data.d.results[i].Title;
	  var id = data.d.results[i].Employee_x0020_ID;
	  var designation=data.d.results[i].Designation;
	  $("#Result").append("
<tr>
<td>"+title+"</td>
<td>"+id+"</td>
<td>"+designation+"</td>
</tr>
");
	}
	},
 	error: function (data) {
	console.log(data.responseJSON.error) 
	}
});
}
</script>
<table id="Result" border="1" cellspacing="5" cellpadding="5" width="100%"></table>

RESULT:

READ

Create Operation:

<script src="/SiteAssets/jquery.min.js"></script>
<script>
function createItem()
{
 var addNewItemUrl = "/_api/Lists/GetByTitle('Employee Details')/Items";
 var itemType = GetItemTypeForListName('Employee_x0020_Details');
 var empId = $("#Id").val();
 var empName=$("#Title").val();
 var empDesgn=$("#Designation").val();
 var item = {
  "__metadata": {"type": itemType },
  "Title": empName,
  "Employee_x0020_ID": empId,
  "Designation":empDesgn,
  };
 addNewItem(addNewItemUrl, item);
}
function addNewItem(url, data) {
 $.ajax({
  url: _spPageContextInfo.webAbsoluteUrl + url,
  type: "POST",
  headers: {
   "accept": "application/json;odata=verbose",
   "X-RequestDigest": $("#__REQUESTDIGEST").val(),
   "content-Type": "application/json;odata=verbose"
   },
  data: JSON.stringify(data),
  success: function (data) {
  alert("Record Added");
  },
  error: function (error) {
  console.log(JSON.stringify(error));
  }
 });
}
function GetItemTypeForListName(name) {
return "SP.Data."+ name.charAt(0).toUpperCase() + name.slice(1) +"ListItem";
}
</script>
<table>
<tr>
<td> <label for"Id">Employee ID:</label></td>
<td><input type"text" id="Id"/></td>
</tr>
<tr>
<td><label for="Title">Employee Name:</label></td>
<td><input type="text" id="Title"/></td>
</tr>
<tr>
<td><label for="Designation">Designation:</label></td>
<td><input type="text" id="Designation"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Add" onclick="createItem()"/></td>
</tr>
</table>

RESULT:

Update Operation:

<script src="/SiteAssets/jquery.min.js"></script>
<script>
function update()
{
 var empId = $("#Id").val();
 var empDesgn=$("#Designation").val();
 var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee Details')/getItemById(" + empId + ")";
 var itemType = GetItemTypeForListName('Employee_x0020_Details');
 var item = {
         "__metadata": { "type": itemType },
         "Designation": empDesgn,
          };
 UpdateData(requestUri,item);
}
function UpdateData(requestUri,item)
{
 $.ajax({
 url: requestUri,
 type: "POST",
 data:JSON.stringify(item),
 headers: {
 "accept":"application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "X-HTTP-Method": "MERGE",
 "IF-MATCH":"*"
 },
 success: function (data) {
             alert("Record Updated");
         },
           error: function (error) {
            console.log(JSON.stringify(error));
         }
 });
}
function GetItemTypeForListName(name) {
 return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}
</script>
<table>
<tr>
<td><label for="ID">Employee ID:</label></td>
<td><input type="text" id="Id"/></td>
</tr>
<tr>
<td><label for="Designation">Designation:</label></td>
<td><input type="text" id="Designation"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Update" onclick="update()"/></td>
<tr></table>

RESULT:

Delete Operation:

<script src="/SiteAssets/jquery.min.js"></script>
<script>
function Delete()
{
 var empId = $("#Id").val();
 var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee Details')/getItemById(" + empId + ")";
 DeleteItem(requestUri);
}
function DeleteItem(deleteuri)
{
 $.ajax({
 url: deleteuri,
 type: "POST",
 headers: {
 "accept":"application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "X-HTTP-Method": "DELETE",
 "IF-MATCH":"*"
 },
 success: function (data) {
             alert("Record Deleted");
         },
         error: function (error) {
            console.log(JSON.stringify(error)); 
        }
 });
}

</script>
<table>
<tr>
<td><label for="ID">Employee ID:</label></td>
<td><input type="text" id="Id"/></td>
</tr>
<tr>
<td colspan="2"><input type="button"  value="Delete" onclick="Delete()"/></td>
<tr></table>

RESULT:

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s