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

Monday, November 9, 2015

Using AngularJS and REST to display list data in SharePoint hosted app

AngularJS is now best way to work on the MVC pattern at client side. In this post, I will walk you through how we can display the data from a SharePoint list in a SharePoint hosted app using AngularJS and SharePoint REST. My assumption is that you have basic understanding of AngularJS and SharePoint REST.
  • Create a SharePoint hosted app.
  • Create a Contacts List in app web.
  • Add a reference of AngularJS to default.aspx
In the default.aspx, add the below code.

  <div ng-app="myApp">  
     <div ng-controller="customersCtrl">  
       <table>  
         <tr>  
           <th>Last Name</th>  
           <th>First Name</th>  
         </tr>  
         <tr ng-repeat="x in Contacts">  
           <td>{{ x.Title }}</td>  
           <td>{{ x.FirstName }}</td>  
         </tr>  
       </table>  
     </div>  
   </div>  

In the above code, ng-app is used to specify that its an AngularJS app and ng-controller is the controller.

Add the below code in the App.JS file.


 'use strict';  
 var myapp = angular.module('myApp', []);  
 myapp.controller('customersCtrl', function ($scope, $http) {  
   var restUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Contacts')/items?$select=Title,FirstName"; 
   $http({  
     method: "GET",  
     url: restUrl,  
     headers: { "Accept": "application/json;odata=verbose" }  
   }).success(function (data) {  
     $scope.Contacts = data.d.results;  
   }).error(function (sender,args) {  
     alert("Error:" + args.message);  
   });  
 });  
 function getQueryStringParameter(paramToRetrieve) {  
   var params =  
   document.URL.split("?")[1].split("&");  
   var strParams = "";  
   for (var i = 0; i < params.length; i = i + 1) {  
     var singleParam = params[i].split("=");  
     if (singleParam[0] == paramToRetrieve)  
       return singleParam[1];  
   }  
 }  

Change the restUrl to below if you wanted to query Host Web.

   var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

   var restUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.AppContextSite(@target)" + "/web/lists/getbytitle('Contacts')/items?$select=Title,FirstName,Company" +  "&@target='" + hostUrl + "'";


In the above code, we are getting the results from the contacts lists and assigning it to Contacts collection of $scope.
Add few items in the contacts lists by navigating to Lists/Contacts url






















Run the code, the results of the code is something like below


Friday, June 20, 2014

Get list items using REST in SharePoint 2013

While using REST in SharePoint, the most important thing is to build the URI. The format of URI is discussed in my last post. Now lets work with the URI format to return different results from list.

Lets create a Contacts list with one more additional column DOB of type Date. Add few items in it, the list will look like below.

  • Get all the items from list


 jQuery(function($) {  
       ReadAllItems();  
 });  
 function ReadAllItems()  
 {  
      jQuery.ajax({  
           url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items",  
           type:"GET",  
            headers: { "Accept": "application/json; odata=verbose" },  
        success: function (data) {  
           DisplayItems(data);  
     },  
     error: function (err) {  
       alert(JSON.stringify(err));  
     }  
      });  
 }  
 function DisplayItems(data)  
 {  
   var results = data.d.results;  
   var html="<table width='70%'><tr><td>ID</td><td>FirstName</td><td>LastName(Title)</td><td>Company</td><td>DOB</td>"  
   for(var i=0; i<results.length; i++) {  
           html+="<tr>"      
     html+="<td>"+results[i].ID+ "</td>";  
     html+="<td>"+results[i].FirstName+ "</td>";  
     html+="<td>"+results[i].Title+ "</td>";  
     html+="<td>"+results[i].Company+ "</td>";  
     html+="<td>"+results[i].DOB+ "</td>";  
     html+="</tr>"      
   }  
   html+="</table>";  
   $('#divMain').html(html);  
 }  

The result of above code will look like this 


  •  Get All Items with selected columns
Get the columns which are required by using $select 
Replace the url paramter above with the code below

url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
        +"?$select=Id,FirstName",






  • Order by FirstName ASC
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$orderby=FirstName",
  • Order by FirstName DESC
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$orderby=FirstName desc",
  • Get The Top rows
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$top=2",
  • Filter by Column
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$filter=FirstName eq 'Akash'",
  • Startswith
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$filter=startswith(FirstName,'Ak')",

  • Substringof
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$filter=substringof('k',FirstName)",
  • AND Condition
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$filter=startswith(FirstName,'A') and Title eq 'Karda'",
  • OR Condition
url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
+"?$select=Id,FirstName,Title,Company,DOB"
+"&$filter=startswith(FirstName,'N') or Title eq 'Karda'",
    • Date Time Column Filter 
    url:_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists/getByTitle('Contacts')/items"
    +"?$select=Id,FirstName,Title,Company,DOB"
    +"&$filter=DOB eq '2012-05-17T07:00:00Z'",

    An Introduction : REST in SharePoint 2013

    SharePoint 2013 introduces a Representational State Transfer (REST) service.  You can interact remotely with SharePoint data by using any technology that supports REST web requests. You can now perform Create, Read, Update, and Delete (CRUD) operations for SharePointfrom remote application using REST web technologies and standard Open Data Protocol (OData) syntax. The remote application must be obtain autorized access. Check this MSDN article that covers Authorization and Authentication using ODATA. REST also used Client.svc to perform SharePoint Operations.

    To use REST capabilities, you need contruct the HTTP request using OData standard.

    If you want to do this to an endpoint
    Use this HTTP request
    Read a resource
    GET
    Create or update a resource
    POST
    Use POST to create entities such as lists and sites. The SharePoint 2013 REST service supports sending POSTcommands that include object definitions to endpoints that represent collections.
    For POST operations, any properties that are not required are set to their default values. If you attempt to set a read-only property as part of a POST operation, the service returns an exception.
    Update or insert a resource
    PUT
    Use PUT and MERGE operations to update existing SharePoint objects.
    Any service endpoint that represents an object property set operation supports both PUT requests andMERGE requests.
    ·         For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property.
    ·         For PUT requests, if you do not specify all required properties in object updates, the REST service returns an exception. In addition, any optional properties you do not explicitly set are set to their default properties.
    Delete a resource
    DELETE
    Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object represented by that endpoint.
    In the case of recyclable objects, such as lists, files, and list items, this results in a Recycle operation.

    URI structure:


    To access SharePoint resource, you must build the URI endpoint. Check the image for URI syntax





    OData Query operators supported in SharePoint 2013:

    Supported
    Not supported
    Numeric comparisons
       Lt
       Le
       Gt
       Ge
       Eq
       Ne
    Arithmetic operators
    (Add, Sub, Mul, Div, Mod)
    Basic math functions
    (round, floor, ceiling)
    String comparisons
      startsWith
      substringof
      Eq
      Ne
    endsWith
    replace
    substring
    tolower
    toupper
    trim
    concat
    Date and time functions
      day()
      month()
      year()
      hour()
      minute()
      second()
    DateTimeRangesOverlap operator
    Querying as to whether a date time falls inside a recurrent date time pattern

    The figure below shows the supported OData query options.

    In The next few posts, I will perform some basic operation using REST api.