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