CRUD Operation In SharePoint Using REST API

Introduction
 
You can perform basic Create, Read, Update and Delete (CRUD) operations by using the Representational State Transfer (REST) interface provided by SharePoint.
 
REST interface exposes all SharePoint entities and the operations, which are available in the other SharePoint client APIs.
 
One advantage of using REST is that you don't have to add references to any SharePoint libraries or the client assemblies. Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as Webs, lists and list items.  
 
SharePoint REST Service architecture
 
 

Complete basic operation 

Basically, we are doing three operations in SharePoint: line Insert, Update and Delete items in a list. We can access the data by using any technology, which supports REST Web request and Open Data Protocol (OData) syntax. This means that you can do everything just making HTTP requests to the dedicated endpoints. Available HTTP methods are GET, POST, PUT, MERGE and PATCH. The supported data format is ATOM (XML based) or JSON.
  • READ- HTTP GET method is used for any kind of read operation.
  • CREATE- Any kind of create operation like list, list item, site and so on maps to the HTTP POST method.
  • UPDATE- To update existing SharePoint 2013 objects, there are three HTTP methods like PUT, PATCH and MERGE available.
  • DELETE- HTTP DELETE method is used to delete any objects in SharePoint 2013. 
Commnands Used to basic Operation
 

URL

Description

HTTP Method

/_api/Web/Lists

Retrieving all the lists in a site and adding new lists

GET, POST

/_api/Web/Lists/GetByTitle('listname')

Getting list details by its title and updating it as well. If anyone changes your list title, your code will break.

GET, POST

/_api/Web/Lists(guid'guid id of your list')

Same as above but changing list title will not affect the code.

GET, POST

/_api/Web/Lists/GetByTitle(' listname ')/Fields

Retrieving all fields associated with a list and add new fields

GET, POST

/_api/Web/Lists/GetByTitle('listname')/

Fields/GetByTitle('fieldname')

Getting details of a field, modifying and deleting it.

GET, PUT, PATCH, MERGE, DELETE

/_api/web/lists/GetByTitle('listname')

/GetItemById(itemId)

This endpoint can be used to get, update and delete a single item.

GET, PUT, PATCH, MERGE, DELETE

/_api/Web/Lists/GetByTitle('listname')

/Items

Retrieving all the items in a list and adding the new items

GET, POST

 
Example

 
  1. <style>    
  2. table, td, th {    
  3.     border: 1px solid green;   
  4.      
  5.    
  6. }    
  7.     
  8. th {    
  9.     background-color: green;    
  10.     color: white;    
  11. }    
  12. .textbox {   
  13.     padding: 7px;  
  14.     width: 50%;  
  15.     margin-bottom: 20px;  
  16.     margin-top: 10px;  
  17.   }   
  18. </style>    
  19.   
  20.   
  21.   
  22. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>    
  23. <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>    
  24.  <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
  25. <script>    
  26.         
  27.     var getLastItemId;  
  28.     var myAngApp = angular.module('SharePointAngApp', []);    
  29.     myAngApp.controller('spCustomerController', function ($scope, $http,$window) {    
  30.   
  31.    $scope.showForm = false;  
  32.      
  33.    $scope.createNewUser = function(){  
  34.     $scope.showForm = true;  
  35.      
  36.   $scope.buttonText = "Save";  
  37.     $scope.companies[0]["Id"] = $scope.companies[0]["ID"];  
  38.     $scope.manufactrers[0]["Id"] = $scope.manufactrers[0]["ID"];  
  39.     $scope.editCustomerObj = {"CompanyName0":$scope.companies[0],"ManufacturerName0":$scope.manufactrers[0]};   
  40.    };  
  41.   
  42.    $scope.editUser = function(custObj){  
  43.         $scope.showForm = true;  
  44.         $scope.buttonText = "Update";  
  45.         $scope.editCustomerObj = {"ID":custObj.ID,"ProductName":custObj.ProductName,"CompanyName0":custObj.CompanyName0,  
  46.                                  "ManufacturerName0":custObj.ManufacturerName0,"SalesOrderNumber":custObj.SalesOrderNumber,"PONo":custObj.PONo};  
  47.          
  48.   
  49.    };  
  50.   
  51.    $scope.CloseDiv = function(){  
  52.     $scope.showForm = false;  
  53.    };  
  54.    getData();  
  55.    getCompany();  
  56.   getManufacturer();  
  57.   
  58.   function getData()  
  59. {  
  60.   var _spPageContextInfo={"webAbsoluteUrl":"https://xyz.sharepoint.com/sites/TESTSITE" }  
  61. /* GET code*/  
  62.         $http({    
  63.             method: 'GET',    
  64.               
  65. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('LicensingInformation')/items?$select=ID,CompanyName0/Id,CompanyName0/Company_x0020_Name,ManufacturerName0/Manufacturer_x0020_Name,ManufacturerName0/Id,Attachments,AttachmentFiles,ProductName,PONo,Created,Author/Title,Modified,SalesOrderNumber&$expand=ManufacturerName0/Manufacturer_x0020_Name, CompanyName0/Company_x0020_Name,Author/Id,AttachmentFiles",    
  66.               
  67.   
  68. headers: { "Accept": "application/json;odata=verbose" }    
  69.   
  70.         }).success(function (data, status, headers, config) {    
  71.   
  72.      
  73.   
  74.             $scope.customers = data.d.results;    
  75.   
  76.   
  77.         }).error(function (data, status, headers, config) {    
  78.            
  79.         });   
  80.   
  81. /* End of GET code*/  
  82. }  
  83.   
  84. function getCompany()  
  85. {  
  86.   var _spPageContextInfo={"webAbsoluteUrl":"https://xyz.sharepoint.com/sites/TESTSITE" }  
  87. /* GET code*/  
  88.         $http({    
  89.             method: 'GET',    
  90.               
  91. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('CompanyDetails')/items?$select=Company_x0020_Name,ID",    
  92.               
  93.   
  94. headers: { "Accept": "application/json;odata=verbose" }    
  95.   
  96.         }).success(function (data, status, headers, config) {    
  97.   
  98.      
  99.   
  100.             $scope.companies = data.d.results;  
  101.             $scope.companies.unshift({"ID":"0","Company_x0020_Name":"--Select Company--"});  
  102.   
  103.   
  104.         }).error(function (data, status, headers, config) {   
  105.   
  106.              alert('error :\n' + JSON.stringify(data));  
  107.              $scope.error = "An error has occured while loading! " + data;    
  108.            
  109.         });   
  110.   
  111. /* End of GET code*/  
  112. }  
  113.   
  114. function getManufacturer()  
  115. {  
  116.   var _spPageContextInfo={"webAbsoluteUrl":"https://xyz.sharepoint.com/sites/TESTSITE" }  
  117. /* GET code*/  
  118.         $http({    
  119.             method: 'GET',    
  120.               
  121. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Manufacturer Details')/items?$select=Manufacturer_x0020_Name,ID",    
  122.               
  123.   
  124. headers: { "Accept": "application/json;odata=verbose" }    
  125.   
  126.         }).success(function (data, status, headers, config) {    
  127.   
  128.      
  129.   
  130.             $scope.manufactrers = data.d.results;    
  131.            $scope.manufactrers.unshift({"ID":"0","Manufacturer_x0020_Name":"--Select Manufacture Name--"});   
  132.   
  133.   
  134.         }).error(function (data, status, headers, config) {   
  135.   
  136.              alert('error :\n' + JSON.stringify(data));  
  137.              $scope.error = "An error has occured while loading! " + data;    
  138.            
  139.         });   
  140.   
  141. /* End of GET code*/  
  142. }  
  143.   
  144. $scope.Delete=function(custObj)  
  145. {  
  146. deleteUser = $window.confirm('Are you sure you want to delete this item ?');  
  147. if(deleteUser){  
  148. var urlvalueDelete_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('LicensingInformation')/items("+custObj.ID+")";  
  149.  var digest = document.getElementById('__REQUESTDIGEST').value;  
  150.         $http({            
  151.             method: 'POST',   
  152.             url: urlvalueDelete,  
  153.             headers: {'X-RequestDigest': digest, 'Content-Type': 'application/json;odata=verbose',  
  154.             'Accept': 'application/json;odata=verbose',"X-HTTP-Method": "DELETE","If-Match": "*"}  
  155.         }).success(function (data, status, headers, config) {    
  156.              
  157.             
  158.             $scope.customers = data.d.results;   
  159.             getData();  
  160.         }).error(function (data, status, headers, config) {   
  161.             alert('error :\n' + JSON.stringify(data));  
  162.              $scope.error = "An error has occured while Deleting! " + data;   
  163.               getData();  
  164.         });  
  165.               getData();  
  166.     }  
  167.      getData();  
  168. }  
  169.   
  170.  function getLastItemID()  
  171. {  
  172.   var _spPageContextInfo={"webAbsoluteUrl":"https://xyz.sharepoint.com/sites/TESTSITE" }  
  173. /* GET code*/  
  174.         $http({    
  175.             method: 'GET',    
  176.               
  177. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('LicensingInformation')/items?$top=1&$orderby=Id%20desc",    
  178.               
  179.   
  180. headers: { "Accept": "application/json;odata=verbose" }    
  181.   
  182.         }).success(function (data, status, headers, config) {    
  183.   
  184.             var lnt = data.d.results.length;  
  185.   
  186.              for(var i=0; i<lnt; i++ ){  
  187.   
  188.   
  189.              getLastItemId = data.d.results[i].ID;  
  190.               
  191.              
  192.             documentUpload(getLastItemId);  
  193. }  
  194.   
  195.         }).error(function (data, status, headers, config) {   
  196.   
  197.              alert('error :\n' + JSON.stringify(data));  
  198.              $scope.error = "An error has occured while loading! " + data;    
  199.            
  200.         });   
  201.   
  202. /* End of GET code*/  
  203. }  
  204.   
  205. function documentUpload(lastItemId) {  
  206.   
  207.   
  208.   var copyID=lastItemId;  
  209.   
  210.         var _spPageContextInfo={"webAbsoluteUrl":"https://xyz.sharepoint.com/sites/TESTSITE" }  
  211.   
  212.   
  213.   
  214.              
  215.                     //Reading the Uploadef file values  
  216.                     var parts = document.getElementById("fileToUpload").value.split("\\");  
  217.                     var filename = parts[parts.length - 1];  
  218.                     var file = document.getElementById("fileToUpload").files[0];  
  219.                     //TestList - is our Listname  
  220.                     //1 - is our List Item ID  
  221.                     //filename - File Name of the attachment  
  222.                     //file - file data  
  223.   
  224.                       
  225.                     uploadFileSP("LicensingInformation",copyID, filename, file);  
  226.                  
  227.               
  228.                      
  229.               
  230.         }  
  231.         function getFileBuffer(file) {  
  232.             var deferred = $.Deferred();  
  233.             var reader = new FileReader();  
  234.             reader.onload = function (e) {  
  235.                 deferred.resolve(e.target.result);  
  236.             }  
  237.             reader.onerror = function (e) {  
  238.                 deferred.reject(e.target.error);  
  239.             }  
  240.             reader.readAsArrayBuffer(file);  
  241.             return deferred.promise();  
  242.         }        
  243.         function uploadFileSP(listName, id, fileName, file) {  
  244.             var deferred = $.Deferred();  
  245.             getFileBuffer(file).then(  
  246.               function (buffer) {  
  247.                   var bytes = new Uint8Array(buffer);  
  248.                   var content = new SP.Base64EncodedByteArray();  
  249.                   var queryUrl = _spPageContextInfo.webAbsoluteUrl  + "/_api/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles";  
  250.                   $.ajax({  
  251.                       url: queryUrl,  
  252.                       type: "POST",  
  253.                       processData: false,  
  254.                       contentType: "application/json;odata=verbose",  
  255.                       data: buffer,  
  256.                       headers: {  
  257.                           "accept": "application/json;odata=verbose",  
  258.                           "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  259.                           "content-length": buffer.byteLength  
  260.                       }, success: onQuerySucess,  
  261.                       error: onQueryFailure  
  262.                   });  
  263.               },  
  264.                 function (err) {  
  265.                     deferred.reject(err);  
  266.                 });  
  267.             return deferred.promise();  
  268.         }  
  269.   
  270.         function onQuerySucess() {  
  271.             alert('Item Added Successfully');  
  272.             getData() ;  
  273.              
  274.         }  
  275.   
  276.         function onQueryFailure(error) {  
  277.             alert("Failure:" + error.status + "," + error.statusText);  
  278.         }  
  279.   
  280. function updateFileSP(listName, id, fileName, file) {  
  281.             var deferred = $.Deferred();  
  282.             getFileBuffer(file).then(  
  283.               function (buffer) {  
  284.                   var bytes = new Uint8Array(buffer);  
  285.                   var content = new SP.Base64EncodedByteArray();  
  286.                   var queryUrl = _spPageContextInfo.webAbsoluteUrl  + "/_api/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')";  
  287.                   $.ajax({  
  288.                       url: queryUrl,  
  289.                       type: "POST",  
  290.                       processData: false,  
  291.                       contentType: "application/json;odata=verbose",  
  292.                       data: buffer,  
  293.                       headers: {  
  294.                           "accept": "application/json;odata=verbose",  
  295.                           "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  296.                           "content-length": buffer.byteLength  
  297.                       }, success: onQuerySucess,  
  298.                       error: onQueryFailure  
  299.                   });  
  300.               },  
  301.                 function (err) {  
  302.                     deferred.reject(err);  
  303.                 });  
  304.             return deferred.promise();  
  305.         }  
  306.   
  307.         function onQuerySucess() {  
  308.             alert('Item Update Successfully');  
  309.             getData() ;  
  310.              
  311.         }  
  312.   
  313.         function onQueryFailure(error) {  
  314.             alert("Failure:" + error.status + "," + error.statusText);  
  315.         }  
  316.   
  317.   
  318.   
  319. $scope.Save = function(custObj){  
  320.   
  321.     var urlValue = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('LicensingInformation')/items";  
  322.     var digest = document.getElementById('__REQUESTDIGEST').value;  
  323.       
  324.     var newCustObj = {'PONo':custObj.PONo,'SalesOrderNumber':custObj.SalesOrderNumber,'ProductName':custObj.ProductName};  
  325.      if(custObj.CompanyName0)  
  326.       newCustObj.CompanyName0Id=custObj.CompanyName0.Id;  
  327.   
  328.   if(custObj.ManufacturerName0)  
  329.       newCustObj.ManufacturerName0Id = custObj.ManufacturerName0.Id;  
  330.   
  331.   
  332.     newCustObj.__metadata = { "type": 'SP.Data.InfoPathListListItem' };  
  333.     if($scope.buttonText == 'Save'){  
  334.       alert('url : ' + urlValue);  
  335.         $http({    
  336.             method: 'POST',   
  337.             url: urlValue,  
  338.             data: newCustObj,  
  339.             headers: {'X-RequestDigest': digest, 'Content-Type': 'application/json;odata=verbose',  
  340.             'Accept': 'application/json;odata=verbose'}  
  341.         }).success(function (data, status, headers, config) {    
  342.              
  343.             $scope.customers = data.d.results;   
  344.             getData() ;  
  345.             getLastItemID();           
  346.            ;  
  347.         }).error(function (data, status, headers, config) {   
  348.             alert('error :\n' + JSON.stringify(data));  
  349.              $scope.error = "An error has occured while adding! " + data;   
  350.         });  
  351.     }  
  352.     else{  
  353.   
  354.         var urlvalueUpdate_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('LicensingInformation')/items("+custObj.ID+")";  
  355.         $http({    
  356.             method: 'POST',   
  357.             url: urlvalueUpdate,  
  358.             data: newCustObj,  
  359.             headers: {'X-RequestDigest': digest, 'Content-Type': 'application/json;odata=verbose',  
  360.             'Accept': 'application/json;odata=verbose',"X-HTTP-Method": "MERGE","If-Match": "*"}  
  361.         }).success(function (data, status, headers, config) {    
  362.             if(true){  
  363.               documentUpload(custObj.ID);             
  364.             }   
  365.                
  366.             $scope.customers = data.d.results;   
  367.             alert('Item Update Successfully');  
  368.             getData() ;  
  369.         }).error(function (data, status, headers, config) {   
  370.             alert('error :\n' + JSON.stringify(data));  
  371.              $scope.error = "An error has occured while Updating! " + data;   
  372.         });  
  373.              
  374.     }  
  375. };  
  376. $scope.uploadAttachment = function(fileElement, customerID){  
  377.   var parts = fileElement.value.split("\\");  
  378.   var filename = parts[parts.length - 1];  
  379.   var file = fileElement.files[0];  
  380.   updateFileSP("LicensingInformation",customerID, filename, file);  
  381. }  
  382.     });    
  383.     
  384. </script>  
  385.   
  386.   
  387. <h1><b> Licensing Information!!</b></h1>    
  388.     
  389. <div ng-app="SharePointAngApp" class="row">    
  390.     <div ng-controller="spCustomerController" class="span10">    
  391.   
  392.   
  393.    <input type="text" class="textbox" ng-model="q" placeholder="Search Items">  
  394.   
  395.   
  396.         <table class="table table-condensed table-hover">    
  397. <thead>  
  398.             <tr>    
  399.                 <th>Company Name</th>  
  400.                 <th>Manufacturer Name</th>                 
  401.                 <th>Product Name</th>    
  402.                 <th>Sales Order Number</th>  
  403.                 <th>PO No</th>  
  404.   
  405.                 <th>Created</th>    
  406.                 <th>Created By</th>  
  407.                 <th>Modified</th>  
  408.                 <th>Blob Items</th>  
  409.                 <th style="width:20px;"> </th>  
  410.                 <th style="width:40px;"> </th>  
  411.                  
  412.                    
  413.                </tr>   </thead>  
  414.   
  415.            <tbody> <tr ng-repeat="customer in customers | filter:q">    
  416.                  <td>{{customer.CompanyName0.Company_x0020_Name}}</td>   
  417.                 <td>{{customer.ManufacturerName0.Manufacturer_x0020_Name}}</td>  
  418.                 <td>{{customer.ProductName}}</td>                              
  419.                   
  420.                 <td>{{customer.SalesOrderNumber}}</td>  
  421.                 <td>{{customer.PONo}}</td>   
  422.   
  423.                 <td>{{customer.Created}}</td>                              
  424.                   
  425.                 <td>{{customer.Author.Title}}</td>  
  426.   
  427.                 <td>{{customer.Modified}}</td>   
  428.                
  429.                 <td><a href="{{customer.AttachmentFiles.results[0].ServerRelativeUrl}}">{{customer.AttachmentFiles.results[0].FileName}}</a><input type="file" name="fileToUpload" id="fileToUpload{{$index}}" onchange="angular.element(this).scope().uploadAttachment(this, {{customer.ID}})" > </td>   
  430.    
  431.   
  432.                 <td><b><a ng-click="editUser(customer)" >Edit</a></b></td>  
  433.                 <td><b><a ng-click="Delete(customer)" >Delete</a><b></td></tbody>  
  434.                 
  435.                          
  436.   
  437.                  
  438.                  
  439.                   
  440.                 </tr>    
  441.   
  442.    
  443.   
  444.         </table>   
  445.        <b><a ng-click="createNewUser()" class="btn btn-small">Create New</a> </b>  
  446.   
  447.       
  448.   
  449. <div ng-show="showForm"  align="left">   
  450.         <p class="divHead"></p>  
  451.         <table>  
  452.             <tr>  
  453.                 <td><b>Company Name</b>  
  454.    
  455.               </td>  
  456.                 <td>  
  457.                      <select ng-model="editCustomerObj.CompanyName0.Id" ng-options="company.ID as company.Company_x0020_Name for company in companies">  
  458.              </select>  
  459.              
  460.                 </td>  
  461.             </tr>  
  462.             <tr>  
  463.                 <td><b>Manufacturer Name</b></td>  
  464.                 <td>  
  465.             <select ng-model="editCustomerObj.ManufacturerName0.Id" ng-options="manufacturer.ID as manufacturer.Manufacturer_x0020_Name for manufacturer in manufactrers">  
  466.              
  467.              </select>  
  468.                 </td>  
  469.             </tr>  
  470.             <tr>  
  471.                 <td><b>Product Name</b></td>  
  472.                 <td>  
  473.                     <input type="text" ng-model="editCustomerObj.ProductName" />  
  474.                 </td>  
  475.             </tr>  
  476.             <tr  >  
  477.                 <td><b>Sales Order Number</b></td>  
  478.                 <td>  
  479.                     <input type="text" ng-model="editCustomerObj.SalesOrderNumber" />  
  480.                 </td>  
  481.             </tr>  
  482.               <tr>  
  483.                 <td><b>PO No</b></td>  
  484.                 <td>  
  485.                     <input type="text" ng-model="editCustomerObj.PONo" />  
  486.                 </td>  
  487.             </tr>   
  488.              <tr>  
  489.                 <td><b>Blob Items</b></td>  
  490.                 <td>  
  491.                     <input type="file" name="fileToUpload" id="fileToUpload">  
  492.                 </td>  
  493.             </tr>   
  494.             <tr>  
  495.                 <td colspan="2">  
  496.                     <input type="button" class="btnAdd" value="{{buttonText}}" ng-click="Save(editCustomerObj)"  />  
  497.                    <input type="button" class="btnCancel" value="Close" ng-click="CloseDiv()" />  
  498.                 </td>  
  499.                  
  500.             </tr>  
  501.         </table>  
  502.     </div>  
  503. </div>  
  504. </div>  


Here, I have included AngularJS to insert and update the item in the list, using JSON. When you are clicking Add New button, the second image will be shown in the screen and you are able to add the document inside the document library through JSON and AngularJS.