Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Sunday, April 1, 2018

Authorize Postman to access SharePoint

Authorize Postman to access SharePoint
1. Register Add-In
2. Grant Permissions to Add-In
3. Generate the Access Token
4. Access the SharePoint resource

1. Register Add-In:-
-------------------------
Open below url to create Add-in.
https://sharepointonline01.sharepoint.com/sites/dev2/_layouts/15/appregnew.aspx
Generate Client ID, Client Secret ID and give required as shown below.
After click on Crete button copy Client ID and Client Secret ID in clipboard will use in next step.
2. Grant Permissions to Add-In:-
----------------------------------------
Open below url to give permission to our add-in.
https://sharepointonline01.sharepoint.com/sites/dev2/_layouts/15/appinv.aspx
Enter Client ID in App Id text and click on lookup button to retrieve add-in details.
In permission Request XML text box type below XML syntax as it is to give read permission.

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
</AppPermissionRequests>
After click on 'Create' button then click on 'Trust It' button to trust it.
Tenant Id required in next step, so go to below url to copy Tenant Id. In my case the highlighted text is Tenant Id.
https://sharepointonline01.sharepoint.com/sites/dev2/_layouts/15/appprincipals.aspx?Scope=Web

Tenant Id : caf8f8f2-6ab2-49eb-b6db-2e2f43603ec1

3. Generate the Access Token:-
--------------------------------------
Open Postman tool and perform POST method.
URL : https://accounts.accesscontrol.windows.net/<TenantID>/tokens/OAuth/2 
URL : https://accounts.accesscontrol.windows.net/caf8f8f2-6ab2-49eb-b6db-2e2f43603ec1/tokens/OAuth/2

Apply the below configurations in HEADER.
KEY : Content-Type
VALUE : application/x-www-form-urlencoded

Apply the below configurations in BODY.
KEY : grant_type
SYNTAX : client_credentials
VALUE : client_credentials

KEY : client_id
SYNTAX : ClientID@TenantID
VALUE : 2141cd97-d779-4962-a622-9bbdfb581f0e@caf8f8f2-6ab2-49eb-b6db-2e2f43603ec1

KEY : client_secret
SYNTAX : ClientSecret
VALUE : faAXsOGXcuHCIDYHHt9uFnjAL4pSCJ3vj09cNNZgnBM=

KEY : resource
SYNTAX : resource/SiteDomain@TenantID
VALUE : 00000003-0000-0ff1-ce00-000000000000/sharepointonline01.sharepoint.com@caf8f8f2-6ab2-49eb-b6db-2e2f43603ec1

In this Body configuration this "00000003-0000-0ff1-ce00-000000000000" resource value is common for all SharePoint online product. 
Click on Send button to get access token from SharePoint.
{
    "token_type": "Bearer",
    "expires_in": "3599",
    "not_before": "1522592768",
    "expires_on": "1522596668",
    "resource": "00000003-0000-0ff1-ce00-000000000000/sharepointonline01.sharepoint.com@caf8f8f2-6ab2-49eb-b6db-2e2f43603ec1",
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkZTaW11RnJGTm9DMHNKWEdtdjEzbk5aY2VEYyIsImtpZCI6IkZTaW11RnJGTm9DMHNKWEdtdjEzbk5aY2VEYyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvc2hhcmVwb2ludG9ubGluZTAxLnNoYXJlcG9pbnQuY29tQGNhZjhmOGYyLTZhYjItNDllYi1iNmRiLTJlMmY0MzYwM2VjMSIsImlzcyI6IjAwMDAwMDAxLTAwMDAtMDAwMC1jMDAwLTAwMDAwMDAwMDAwMEBjYWY4ZjhmMi02YWIyLTQ5ZWItYjZkYi0yZTJmNDM2MDNlYzEiLCJpYXQiOjE1MjI1OTI3NjgsIm5iZiI6MTUyMjU5Mjc2OCwiZXhwIjoxNTIyNTk2NjY4LCJpZGVudGl0eXByb3ZpZGVyIjoiMDAwMDAwMDEtMDAwMC0wMDAwLWMwMDAtMDAwMDAwMDAwMDAwQGNhZjhmOGYyLTZhYjItNDllYi1iNmRiLTJlMmY0MzYwM2VjMSIsIm5hbWVpZCI6IjIxNDFjZDk3LWQ3NzktNDk2Mi1hNjIyLTliYmRmYjU4MWYwZUBjYWY4ZjhmMi02YWIyLTQ5ZWItYjZkYi0yZTJmNDM2MDNlYzEiLCJvaWQiOiI0NzdkMmFmZC1kYzMyLTRmMTUtOWFjMi1lYTE1YzFhODJjNzQiLCJzdWIiOiI0NzdkMmFmZC1kYzMyLTRmMTUtOWFjMi1lYTE1YzFhODJjNzQiLCJ0cnVzdGVkZm9yZGVsZWdhdGlvbiI6ImZhbHNlIn0.wGBEO8JkGv9eCbza4CIivJve32l-96rH64rsgmezdLLUo2JZ_aiqGQHI545Z0pDRG4JtghrQIrXJ2NH643wKUjZl__UlX6wkOTu8gEkkUCbU3EtX0I3dKdOFAQl-ehhDAOcwp8oBys3Vw89xseuKkVWePGT-AtJP-sEOk-U3CQuj0w7Ft-BwjXmapcIF5em9kwPa5rPza7teOYdk6qe56LQavZohV_31yykPhWHdNds2jxAUHjWL_xKS3ffidtihTn57z8zvonFwKomDuVdwJrpkOmk4x7ry_wsOLMP5q5-N46yMbe8hZFAWE8k2l5mN4x66LD3MFThPbDAfOvqiMQ"
}

4. Access the SharePoint resource:-
--------------------------------------------
Open postman and perform POST method to read SharePoint site title using access token.

URL : https://sharepointonline01.sharepoint.com/sites/dev2/_api/web?$select=Title

Apply configurations in HEADER.
KEY : Authorization
SYNTAX : <token_type> <access_token>
VALUE : Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkZTaW11RnJGTm9DMHNKWEdtdjEzbk5aY2VEYyIsImtpZCI6IkZTaW11RnJGTm9DMHNKWEdtdjEzbk5aY2VEYyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvc2hhcmVwb2ludG9ubGluZTAxLnNoYXJlcG9pbnQuY29tQGNhZjhmOGYyLTZhYjItNDllYi1iNmRiLTJlMmY0MzYwM2VjMSIsImlzcyI6IjAwMDAwMDAxLTAwMDAtMDAwMC1jMDAwLTAwMDAwMDAwMDAwMEBjYWY4ZjhmMi02YWIyLTQ5ZWItYjZkYi0yZTJmNDM2MDNlYzEiLCJpYXQiOjE1MjI1OTI3NjgsIm5iZiI6MTUyMjU5Mjc2OCwiZXhwIjoxNTIyNTk2NjY4LCJpZGVudGl0eXByb3ZpZGVyIjoiMDAwMDAwMDEtMDAwMC0wMDAwLWMwMDAtMDAwMDAwMDAwMDAwQGNhZjhmOGYyLTZhYjItNDllYi1iNmRiLTJlMmY0MzYwM2VjMSIsIm5hbWVpZCI6IjIxNDFjZDk3LWQ3NzktNDk2Mi1hNjIyLTliYmRmYjU4MWYwZUBjYWY4ZjhmMi02YWIyLTQ5ZWItYjZkYi0yZTJmNDM2MDNlYzEiLCJvaWQiOiI0NzdkMmFmZC1kYzMyLTRmMTUtOWFjMi1lYTE1YzFhODJjNzQiLCJzdWIiOiI0NzdkMmFmZC1kYzMyLTRmMTUtOWFjMi1lYTE1YzFhODJjNzQiLCJ0cnVzdGVkZm9yZGVsZWdhdGlvbiI6ImZhbHNlIn0.wGBEO8JkGv9eCbza4CIivJve32l-96rH64rsgmezdLLUo2JZ_aiqGQHI545Z0pDRG4JtghrQIrXJ2NH643wKUjZl__UlX6wkOTu8gEkkUCbU3EtX0I3dKdOFAQl-ehhDAOcwp8oBys3Vw89xseuKkVWePGT-AtJP-sEOk-U3CQuj0w7Ft-BwjXmapcIF5em9kwPa5rPza7teOYdk6qe56LQavZohV_31yykPhWHdNds2jxAUHjWL_xKS3ffidtihTn57z8zvonFwKomDuVdwJrpkOmk4x7ry_wsOLMP5q5-N46yMbe8hZFAWE8k2l5mN4x66LD3MFThPbDAfOvqiMQ

Sunday, February 25, 2018

DataTable Custom Paging using REST in SharePoint

DataTable Custom Paging using REST in SharePoint.
1. Create 'Employee' list and add some data.
2. Create a script file and add into Site Assets library.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"/>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>       
    <script type="text/javascript">
        var paginateMaxID = "";
        var paginateMinID = "";
        var paginateNext = "Next";
        var paginatePrevious = "Previous";
        var paginateCountPerPage = 3;
        var lstEmployee = 'Employees';      
        $(document).ready(function(){
            GetEmployeeItems(); 
            $("#liPrevious").click(function() {
                DataTablePaginate($("#liPrevious").text().trim());
            });
            $("#liNext").click(function() {
                DataTablePaginate($("#liNext").text().trim());
            }); 
            $("#divPaginationPager").show();
        });
        function GetEmployeeItems(pPreviousOrNext) {
            var url = "";
            var response =  [];     
            if(pPreviousOrNext == undefined) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?$top="+paginateCountPerPage+
                    "&$select=ID,Title,Address&$orderby=ID desc";       
            } else if(pPreviousOrNext==paginateNext) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?"+
                    "$filter=ID gt "+paginateMaxID+"&$top="+paginateCountPerPage+"&$select=ID,Title,Address&$orderby=ID asc";       
            } else if(pPreviousOrNext==paginatePrevious) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?"+
                    "$filter=ID lt "+paginateMinID+"&$top="+paginateCountPerPage+"&$select=ID,Title,Address&$orderby=ID desc";  
            }           
            $.ajax({
                url: url,
                type: "GET",
                headers:
                    Accept: "application/json;odata=verbose" 
                }, 
                async: false,
                cache: false,
                beforeSend: function(){ 
                },
                success: function (data, status, xhr) {
                    if(data.d.results != undefined && data.d.results.length > 0) {
                        response = data.d.results;
                    }           
                    $('#divDataTablePagingEmployee').html("");
                    $('#tblDataTablePagingEmployee').html("");
                    if (response != undefined && response.length > 0) {
                        $('#divDataTablePagingEmployee').append(getDatatable(response,pPreviousOrNext));
                    } else {                        
                         var tableContent =
                            '<table id="tblDataTablePagingEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">'+
                                '<thead>'+
                                    '<tr>'+
                                        '<th class="bg-primary" style="text-align: center; !important">ID</th>'+
                                        '<th class="bg-primary" style="text-align: center; !important">Name</th>'+
                                        '<th class="bg-primary" style="text-align: center; !important">Address</th>'+
                                    '</tr>'+
                                '</thead>'+
                                '<tbody>';
                        tableContent += '<tr>';
                        tableContent += '<td><span>No records found</span></td><td></td><td></td>';
                        tableContent += '</tr>';      
                        tableContent +='</tbody></table>';
                        $('#divDataTablePagingEmployee').append(tableContent);  
                        console.log("no records found");
                    }                       
                    if(!$.fn.DataTable.isDataTable('#tblDataTablePagingEmployee')) {                    
                        var table = $('#tblDataTablePagingEmployee').DataTable({
                            "columnDefs": [{"className": "dt-center", "targets": "_all"}],
                            "pagingType": "simple",
                            "lengthMenu": [[5000, -1], [5000, "All"]],
                            "ordering": false,
                            "order": []                         
                        });
                    }           
                    if($("#tblDataTablePagingEmployee_length").length>0) {
                        $("#tblDataTablePagingEmployee_length").hide();
                    }
                    if($("#tblDataTablePagingEmployee_paginate").length>0) {
                        $("#tblDataTablePagingEmployee_paginate").hide();
                    }
                    if($("#tblDataTablePagingEmployee_info").length>0) {
                        $("#tblDataTablePagingEmployee_info").hide();
                    }
                    if (!(response != undefined && response.length > 0)) {
                        if(pPreviousOrNext==paginateNext) {
                            paginateMinID = paginateMaxID+1;
                            paginateMaxID = "";                     
                            var addClassNextDisabled = $("#liNext").attr('class');
                            if(addClassNextDisabled.indexOf("disabled")<0) { 
                                $("#liNext").addClass("disabled");
                            }                       
                        } else if(pPreviousOrNext==paginatePrevious) {
                            paginateMaxID = paginateMinID-1;
                            paginateMinID= "";
                            var addClassPreviousDisabled = $("#liPrevious").attr('class');
                            if(addClassPreviousDisabled.indexOf("disabled")<0) { 
                                $("#liPrevious").addClass("disabled");
                            }                       
                        }
                    }                   
                },
                error: function (xhr, status, error) {
                    $("#divdanger").text("error: " + xhr.responseText);
                    $("#divdanger").show();       
                },
                complete: function() {
                    if($('#divDataTablePagingEmployee').html()=="") {
                        $('#divDataTablePagingEmployee').append("<span>Item does not exist. It may have been deleted by another user. </span>");
                    }
                } 
            });
        }
        function getDatatable(listData,pPreviousOrNext) {   
            paginateMaxID = "";
            paginateMinID = ""
            var tableContent =
            '<table id="tblDataTablePagingEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">'+
                '<thead>'+
                    '<tr>'+
                        '<th class="bg-primary" style="text-align: center; !important">ID</th>'+
                        '<th class="bg-primary" style="text-align: center; !important">Name</th>'+
                        '<th class="bg-primary" style="text-align: center; !important">Address</th>'+
                    '</tr>'+
                '</thead>'+
                '<tbody>';  
            if(pPreviousOrNext==paginateNext) {
                listData.reverse();
            }       
            for (var i = 0; i < listData.length; i++) {
                if(i == 0) {
                    paginateMaxID = listData[i]["ID"];
                }
                if(i == listData.length-1) {
                    paginateMinID = listData[i]["ID"];
                }                            
                tableContent += '<tr>';
                tableContent += '<td>'+(listData[i]["ID"]!=null&&listData[i]["ID"]!=""?listData[i]["ID"]:"")+'</td>';
                tableContent += '<td>'+(listData[i]["Title"]!=null&&listData[i]["Title"]!=""?listData[i]["Title"]:"")+'</td>';
                tableContent += '<td>'+(listData[i]["Address"]!=null&&listData[i]["Address"]!=""?listData[i]["Address"]:"")+'</td>';
                tableContent += '</tr>';       
            }
            tableContent +='</tbody></table>';   
            return tableContent;
            console.log(tableContent);
        }
        function DataTablePaginate(pPreviousOrNext) {   
            if(pPreviousOrNext == paginateNext) {
                var clsPreviousDisabled = $("#liPrevious").attr('class');
                if(clsPreviousDisabled.indexOf("disabled")>0) { 
                    $("#liPrevious").removeClass("disabled");
                }       
            }
            if(pPreviousOrNext == paginatePrevious) {
                var clsNextDisabled = $("#liNext").attr('class');
                if(clsNextDisabled.indexOf("disabled")>0) { 
                    $("#liNext").removeClass("disabled");
                }
            }                   
            if(($("#liPrevious").attr('class').indexOf("disabled")<0 && pPreviousOrNext == paginatePrevious) ||
               ($("#liNext").attr('class').indexOf("disabled")<0 && pPreviousOrNext == paginateNext)) {
                GetEmployeeItems(pPreviousOrNext);
            }   
        }
    </script>   
</head>
<body>
<p class="h1">DataTable Custom Paging using REST in SharePoint</p>
<div id="divDataTablePagingEmployee"></div>
<div id="divPaginationPager" class="row" style="display:none;">
    <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10"></div>
    <div  class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
          <ul class='pagination'>
            <li class='page-item' id='liPrevious'>
              <a class='page-link' href='#' tabindex='-1'>Previous</a>
            </li>
            <li class='page-item disabled' id='liNext'>
              <a class='page-link' href='#'>Next</a>
            </li>
          </ul>
    </div>
</div>
</body>
</html>

3. Add 'Content Editor' webpart into a page and give content link as above script file url from Site Assets.

4. Check the result.

Featured Post

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide Version: July 2026 | Audience: Beginners, Citizen Developers, Busine...

Popular posts