Save Mutiple Records to SharePoint 2013 Using REST API in a Single Request (Batch Processing)

Requirement

Save more than one record (multiple records) to a SharePoint 2013 list in an App using the REST API in a single request (Batch Processing).
 
Solution

This can be done in one of the following ways:
  1. Traditional Approach:  SharePoint REST API ($batch)
  2. Simplified Approach:  SharePoint REST API + BreezeJs
Note: To explain both these approaches, I am using a SharePoint CustomList named "Employees" with the 3 columns "First Name", "Last Name" and "Email".
 
For both of these approaches SharePoint should receive the data as shown below.
Traditional Approach

SharePoint provides $batch processing that requires the following code snippet to generate the data shown in the preceding format. The following code is attached with this article as RESTAPI_Batch.js.
 
  1. var EmployeesAsJson = [  
  2.             {  
  3.                 __metadata: {  
  4.                     type: 'SP.Data.EmployeesListItem'  
  5.                 },  
  6.                 FirstName: 'User1',  
  7.                 LastName: 'Test1',  
  8.                 Email: '[email protected]'  
  9.             },  
  10.             {  
  11.                 __metadata: {  
  12.                     type: 'SP.Data.EmployeesListItem'  
  13.                 },  
  14.                 FirstName: 'User2',  
  15.                 LastName: 'Test2',  
  16.                 Email: '[email protected]'  
  17.             },  
  18.             {  
  19.                  __metadata: {  
  20.                      type: 'SP.Data.EmployeesListItem'  
  21.                  },  
  22.                  FirstName: 'User3',  
  23.                  LastName: 'Test3',  
  24.                  Email: '[email protected]'  
  25.              }  
  26.     ];  

  1.         var batchGuid = generateUUID();  
  2.   
  3.         // creating the body  
  4.         var batchContents = new Array();  
  5.         var changeSetId = generateUUID();  
  6.   
  7.         // get current host  
  8.         var temp = document.createElement('a');  
  9.         temp.href = _spPageContextInfo.webAbsoluteUrl;  
  10.         var host = temp.hostname;  
  11.   
  12.         // for each employee...  
  13.         for (var employeeIndex = 0; employeeIndex < employeesAsJson.length; employeeIndex++) {  
  14.   
  15.             var employee = employeesAsJson[employeeIndex];  
  16.   
  17.             // create the request endpoint  
  18.             var endpoint = _spPageContextInfo.webAbsoluteUrl  
  19.                            + '/_api/web/lists/getbytitle(\'Employees\')'  
  20.                            + '/items';  
  21.   
  22.             // create the changeset  
  23.             batchContents.push('--changeset_' + changeSetId);  
  24.             batchContents.push('Content-Type: application/http');  
  25.             batchContents.push('Content-Transfer-Encoding: binary');  
  26.             batchContents.push('');  
  27.             batchContents.push('POST ' + endpoint + ' HTTP/1.1');  
  28.             batchContents.push('Content-Type: application/json;odata=verbose');  
  29.             batchContents.push('');  
  30.             batchContents.push(JSON.stringify(employee));  
  31.             batchContents.push('');  
  32.         }  
  33.         // END changeset to create data  
  34.         batchContents.push('--changeset_' + changeSetId + '--');  
  35.   
  36.         // generate the body of the batch  
  37.         var batchBody = batchContents.join('\r\n');  
  38.   
  39.         // create the request endpoint   
  40.         var endpoint = _spPageContextInfo.webAbsoluteUrl  
  41.                        + '/_api/$batch';  
  42.   
  43.         // batches need a specific header  
  44.         var batchRequestHeader = {  
  45.             'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),  
  46.             'Content-Type''multipart/mixed; boundary="batch_' + batchGuid + '"'  
  47.         };  
  48.   
  49.         // create request  
  50.         jQuery.ajax({  
  51.             url: endpoint,  
  52.             type: 'POST',  
  53.             headers: batchRequestHeader,  
  54.             data: batchBody,  
  55.             success: function (response) {  
  56.                 alert("Successfully saved a batch request");  
  57.             },  
  58.             fail: function (error) {  
  59.                 alert('.. create employee FAIL ', error);  
  60.             }  
  61.         });  
Simplified Approach

The code of the preceding content needs a lot amount of time and patience. As an alternate, Breezejs can be used to simplify the formatting and submission of data. We need to reference Breeze libraries in the SharePoint App Page. The following is the reference for that.
 
Here is the code format when using Breeze libraries.  The following code is available with this article as RESTAPI_Breeze.js
  1. // create a new Employees
  2.     function createItem() {  
  3.   
  4.         var Employee1 = entityManager.createEntity(EmployeeType);  
  5.         Employee1.FirstName = 'User1';  
  6.         Employee1.Title = 'Test1';  
  7.         Employee1.Email = '[email protected]';  
  8.       
  9.         var Employee2 = entityManager.createEntity(EmployeeType);  
  10.         Employee2.FirstName = 'User2';  
  11.         Employee2.Title = 'Test2';  
  12.         Employee2.Email = '[email protected]';  
  13.       
  14.         var Employee3 = entityManager.createEntity(EmployeeType);  
  15.         Employee3.FirstName = 'User3';  
  16.         Employee3.Title = 'Test3';  
  17.         Employee3.Email = '[email protected]';  
  18.   
  19.         // save entity  
  20.         entityManager.saveChanges()  
  21.           .then(function () {  
  22.               alert("Successfully saved a batch request");  
  23.           });  
  24.     }  
Future Articles

I will write new article(s) for the following content:
  1. Configuring Breeze to SharePoint 2013 App
  2. Example of Breeze along with code for create, update and delete operations.