Click here to Skip to main content
14,450,486 members

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

Rate this:
5.00 (1 vote)
Please Sign up or sign in to vote.
5.00 (1 vote)
20 Feb 2015CPOL
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.
Image 1

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

// 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)

Share

About the Author

Narula Srinivas
Web Developer
India India
I am a Developer with 7 years experience in different .NET Frameworks,SharePoint 2007/2010,Google Maps,Google Analytics,jQuery,Ajax

Comments and Discussions

 
QuestionI'm testing the solution in sharepoint 2013 but it marks me an error, Can somebody help me? Pin
thecrow_0014-Nov-17 14:15
Memberthecrow_0014-Nov-17 14:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Tip/Trick
Posted 20 Feb 2015

Tagged as

Stats

17.1K views
305 downloads
2 bookmarked