Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Save Mutiple records to SharePoint 2013 using REST API in a single request (Batch Processing)

5.00/5 (1 vote)
20 Feb 2015CPOL1 min read 23.2K   338  
This article gives you the approaches available to save multiple records in a single request (Batch Processing) to SharePoint 2013 list using REST API.

Requirement

Save more than one record / multiple records  to SharePoint 2013 list which is a part of App using REST API in a single request(Batch Processing).

Solution

This can be achieved using 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 SharePoint CustomList named "Employees" with 3 columns as "First Name","Last Name" and "Email.
 
For both these approaches SharePoint should receive data as shown below.

Traditional Approach

SharePoint provided $batch processing which requires below code snippet to generate data shown in above format. Below code is attached with this article as RESTAPI_Batch.js

    var EmployeesAsJson = [
            {
                __metadata: {
                    type: 'SP.Data.EmployeesListItem'
                },
                FirstName: 'User1',
                LastName: 'Test1',
                Email: 'User1.Test1@email.com'
            },
            {
                __metadata: {
                    type: 'SP.Data.EmployeesListItem'
                },
                FirstName: 'User2',
                LastName: 'Test2',
                Email: 'User2.Test2@email.com'
            },
            {
                 __metadata: {
                     type: 'SP.Data.EmployeesListItem'
                 },
                 FirstName: 'User3',
                 LastName: 'Test3',
                 Email: 'User3.Test3@email.com'
             }
    

// generate a batch boundary
        var batchGuid = generateUUID();

        // creating the body
        var batchContents = new Array();
        var changeSetId = generateUUID();

        // get current host
        var temp = document.createElement('a');
        temp.href = _spPageContextInfo.webAbsoluteUrl;
        var host = temp.hostname;

        // for each employee...
        for (var employeeIndex = 0; employeeIndex < employeesAsJson.length; employeeIndex++) {

            var employee = employeesAsJson[employeeIndex];

            // create the request endpoint
            var endpoint = _spPageContextInfo.webAbsoluteUrl
                           + '/_api/web/lists/getbytitle(\'Employees\')'
                           + '/items';

            // create the changeset
            batchContents.push('--changeset_' + changeSetId);
            batchContents.push('Content-Type: application/http');
            batchContents.push('Content-Transfer-Encoding: binary');
            batchContents.push('');
            batchContents.push('POST ' + endpoint + ' HTTP/1.1');
            batchContents.push('Content-Type: application/json;odata=verbose');
            batchContents.push('');
            batchContents.push(JSON.stringify(employee));
            batchContents.push('');
        }
        // END changeset to create data
        batchContents.push('--changeset_' + changeSetId + '--');

        // generate the body of the batch
        var batchBody = batchContents.join('\r\n');

        // create the request endpoint 
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/$batch';

        // batches need a specific header
        var batchRequestHeader = {
            'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
            'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
        };

        // create request
        jQuery.ajax({
            url: endpoint,
            type: 'POST',
            headers: batchRequestHeader,
            data: batchBody,
            success: function (response) {
                alert("Successfully saved a batch request");
            },
            fail: function (error) {
                alert('.. create employee FAIL ', error);
            }
        });

Simplified Approach

Coding of above content needs an 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 SharePoint App Page. Below is the reference for that.

<!-- breeze & dependent libraries -->
<script type="text/javascript" src="../Scripts/q.js"></script>
<script type="text/javascript" src="../Scripts/breeze.debug.js"></script>
<script type="text/javascript" src="../Scripts/breeze.labs.dataservice.abstractrest.js"></script>
<script type="text/javascript" src="../Scripts/breeze.labs.dataservice.sharepoint.js"></script>
<script type="text/javascript" src="../Scripts/breeze.metadata-helper.js"></script>

Here is the code format while using breeze libraries.  Below code is available with this article RESTAPI_Breeze.js

JavaScript
// create a new Employees
    function createItem() {

        var Employee1 = entityManager.createEntity(EmployeeType);
        Employee1.FirstName = 'User1';
        Employee1.Title = 'Test1';
        Employee1.Email = 'User1.Test1@email.com';
    
        var Employee2 = entityManager.createEntity(EmployeeType);
        Employee2.FirstName = 'User2';
        Employee2.Title = 'Test2';
        Employee2.Email = 'User2.Test2@email.com';
    
        var Employee3 = entityManager.createEntity(EmployeeType);
        Employee3.FirstName = 'User3';
        Employee3.Title = 'Test3';
        Employee3.Email = 'User3.Test2@email.com';

        // save entity
        entityManager.saveChanges()
          .then(function () {
              alert("Successfully saved a batch request");
          });
    }

Upcoming Articles

I am going to 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,Delete operations.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)