Saturday, November 29, 2014



We saw how to fetch list items using REST services. We also saw various options and operators which can be applied on REST services while fetching list items. In this post we will see how to add new list item in list.

Adding list item through REST services is very simple, only things to remember are formats of field types, and the parameters to the service. Construct required input data and make REST service call and item gets created.

Following is the code snippet of creating new item in list.

function AddNewItem() 
 { 
var name = $("#txtName").val(); 
var class1 = $("#txtClass").val(); 
var age = $("#txtAge").val(); 
var city = $("#txtCity").val(); 
$.ajax({ 
        url: "/sites/OnePalSh/_api/web/lists/getbytitle('StudentsList')/items",         
        data: JSON.stringify({'__metadata': { 'type': 'SP.Data.StudentsListListItem' }, 'Title': 'Mr.', 'Name': name, 'Class' : class1, 'Age': age,'City': city }), 
        type: "POST",         
        headers: { 
            "ACCEPT": "application/json;odata=verbose", 
            "content-type": "application/json;odata=verbose", 
            "X-RequestDigest": $("#__REQUESTDIGEST").val() 
        }, 
        success: function (data) { 
            self.Students.push(new self.Student(data.d.ID,name,class1,age,city)); 
        }, 
        error: function (error) { 
            alert(JSON.stringify(error)); 
        } 
    }); 
 } 

If you see it closely the REST service URL remains same. There is change in method type, in this case it is POST. To add list item you need to give field values using the parameter: data. In Data you need to provide the metadata which is the type; this is important parameter with which REST service understands the schema of list. And others information in 'data' is nothing but the field values.  

You can get the type from REST service response. Enter the List Get Item's REST URL in browser and in response you will get this value like shown in below image. 


You need to use headers as mentioned above; we will see it in details in coming post.
Happy SharePoint Coding.

Saturday, November 22, 2014


The future in SharePoint development is REST services; there will be very limited scope for server side code development. REST services provide various services to interact with SharePoint server and implement your business rules and logic. In this post we will learn how to fetch the information of current user like Login name, Email address, User Id, etc. We required this information frequently so let’s see how we can get this information.

The REST URL to get the User Information is:

http://[SiteUrl]/_api/web/CurrentUser

This service returns information like below:



JavsScript Code :

var RESTURL = "/_api/web/CurrentUser";
$(document).ready(function () {
    GetLists();
});
function GetLists()
{
 var self = this;
$.ajax({
url: RESTURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (userdata) {
  self.LoginName = userdata.d.LoginName;
  self.Title  = userdata.d.Title;
  self.Email = userdata.d.Email;
  ko.applyBindings(self);
},
error: function (error) {
alert(JSON.stringify(error));
}
});

}

HTML Code:

<script type="text/javascript" src="/Site%20Assets/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/Site%20Assets/js/knockout.3.2.0.js"></script>
<script type="text/javascript" src="/Site%20Assets/js/GetCurrentUser.js"></script>

<div>Current USer Information:
<ul>
<li>
Login name : <span data-bind="text: LoginName"></span>
</li>
<li>
Title : <span data-bind="text: Title"></span>
</li>
<li>
Email : <span data-bind="text: Email"></span>
</li>
</ul>

</div>


Happy SharePoint Coding.


I have explained how to achieve Pagination and Multiple Filters in REST Services in my last posts. Lets see other parameters and options which can be used with REST services. We will start from basic REST url and will take all options one by one.

Following is the simple REST url to get all items of a list. All you have to do is just give the Title if list as shown in below example:

/_api/web/lists/getbytitle('ListName')/items

'$select' :

Above url returns all items with all possible fields or list columns. But what if list has more than 20-30 columns? Its not good practice to get all fields. Get only those field which are required. To achieve this you can use '$select' parameter or option. Below example shows how to use it.

/_api/web/lists/getbytitle('ListName')/items?$select=ID,Title,Age,Name

With the help of select parameter you can tell service just get only those columns which are mentioned.

'$orderby' :

Now what if you want sorted list items. Simple, you can use '$orderby' parameter and provide the field name. REST service will return sorted list items in response.

/_api/web/lists/getbytitle('ListName')/items?$select=ID,Title,Age,Name&$orderby= ID

Above REST will return list item sorted by ID. Use 'desc' or 'asec' to sort them ascending or descending.

/_api/web/lists/getbytitle('ListName')/items?$select=ID,Title,Age,Name&$orderby=ID desc.

'$top' :

Now to get top list items you can use '$top' parameter. This parameter tells REST to return only specified top items in result.

/_api/web/lists/getbytitle('ListName')/items?$select=ID,Title,Age,Name&$orderby=ID desc&$top=5.

This is useful while showing latest items on screen like latest news, articles, announcements, blogs, etc.

'$skip' :

Now lets see how to skip certain items coming in response. To achieve this you can use. '$skip' parameter.

/_api/web/lists/getbytitle('ListName')/items?$select=ID,Title,Age,Name&$orderby=ID desc&$skip=5.

This REST URL skips top 5 records after order by on ID.

'$expand' :

The trickiest part in REST is dealing with people fields and lookup fields. Let’s see one by one.

People Field:

This field internally contains the ID of user from the User Information list. Whenever you make following call you get result like shown below for the User or People field. In this case it is Approver field.

/_api/web/lists/getbytitle('ListName')/items



Strangely it returns ‘ApproverId’! But the list does not have such field? No need to panic, as said People field internally contains id of user or person the REST service returns Approver field as ‘ApproverId’. So let’s say list have custom field: Author, it will return ‘AuthorId’ in response.
What is the proper way to deal with people field? You need to use ‘$expand’ parameter to expand the field. Following REST URL gives you idea how to use $expand.

To get The Login name:

_api/web/lists/getbytitle('StudentsList')/items?$select=Name,Title,Approver/Name&$expand=Approver/Name



To get just Id:

_api/web/lists/getbytitle('StudentsList')/items?$select=Name,Title,Approver/Id&$expand=Approver/Id



Lookup Field:

The same is applicable for Look up field. To work with them you need to expand them. Examples as below:

_api/web/lists/getbytitle('StudentsList')/items?$select=Name,Title,Testlookup/Id&$expand=Testlookup/Id



Happy SharePoint coding.

Tuesday, November 18, 2014


SharePoint REST services are the hot topic these days. From developers perspective they are very simple and straightforward to use. Most of the things cab be achieved through RESTs. In this post we will learn how to implement pagination while reading list items from list.

Its not always good to get all thousands of items from list and show in page. It will make your page behave slowly and will become heavy. The best approach is show limited items at a time and implement pagination. But is this possible if you are using REST service to get list items? You will first start looking for any parameter for pagination.  But you will not find any parameter to send so server can understand which set of items needs to return. Then what is the option?

It is so simple. For this go through the response of first REST Ajax call. If you read each property carefully you will get answer for pagination. Properly "__next" is nothing but the REST url for next page :). Is it simple? Yes. So use "data.d.__next" to get next page items. REST service always returns this property whenever there is possible next set of items otherwise returns null.

To implement pagination $top parameter is important, so in default REST URL define the $top value and then data.d.__next will work properly. it will always return next $top rows.

Default REST URL:

var DEFRESTURL = "/sites/OnePalSh/_api/web/lists/getbytitle('StudentsList')/items?&$top=5";

__NEXT:



Below basic example of pagination will help you to understand implementation.

HTML file:

<script type="text/javascript" src="/sites/OnePalSh/Site%20Assets/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/sites/OnePalSh/Site%20Assets/js/knockout.3.2.0.js"></script>
<script type="text/javascript" src="/sites/OnePalSh/Site%20Assets/js/ShowListItems.js"></script>

<div>

All lists Items:

<div class="table-responsive">
  <table class="table">

<thead>
<th> Name </th>
<th> Class </th>
<th> Age </th>
<th> City </th>
</thead>
<tbody data-bind="foreach: Students">
<tr>

<td>
<span data-bind="text: Name"></span>
</td>

<td>
<span data-bind="text: Class1"></span>
</td>

<td>
<span data-bind="text: Age"></span>
</td>

<td>
<span data-bind="text: City"></span>
</td>

</tr>
</tbody>    

  </table>
</div>
<div class="btn-group">
  <button class="btn" data-bind="click: PreviousItems">Previous</button>
  
  <button class="btn" data-bind="click: GetNextItems">Next</button>
</div>

</div>


JS File:

var DEFRESTURL = "/sites/OnePalSh/_api/web/lists/getbytitle('StudentsList')/items?&$top=5";
var RESTURL = DEFRESTURL;
var urlArr = new Array();

$(document).ready(function () {
urlArr.push(RESTURL);
    GetListItems();
});


function GetListItems()
{

 var self = this;

 self.Student = function(name,class1,age,city)
 {
 var self = this;
 self.Name = name;
 self.Class1 = class1;
 self.Age = age;
 self.City = city;
 }

self.Students = ko.observableArray([]);


 $.ajax({
url: RESTURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
if(data.d.__next != null)
{
urlArr.push(data.d.__next);
}
$.each(data.d.results, function () {
 self.Students.push(new self.Student(this.Name,this.Class,this.Age,this.City));
});
ko.applyBindings(self);
},
error: function (error) {
ko.applyBindings(self);
alert(JSON.stringify(error));
}
 });

 self.GetNextItems = function()
 {
RESTURL = urlArr[urlArr.length - 1];
self.Students.removeAll();

$.ajax({
url: RESTURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
if(data.d.__next != null)
{
urlArr.push(data.d.__next);
}
$.each(data.d.results, function () {
 self.Students.push(new self.Student(this.Name,this.Class,this.Age,this.City));
});

},
error: function (error) {
ko.applyBindings(self);
alert(JSON.stringify(error));
}
 });
 }

 self.PreviousItems = function()
 {
urlArr.pop();
RESTURL = urlArr[urlArr.length - 1];
self.Students.removeAll();

$.ajax({
url: RESTURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
if(data.d.__next != null)
{
urlArr.push(data.d.__next);
}
$.each(data.d.results, function () {
 self.Students.push(new self.Student(this.Name,this.Class,this.Age,this.City));
});

},
error: function (error) {
ko.applyBindings(self);
alert(JSON.stringify(error));
}
 });
 }


}

This way you can do pagination in SharePoint 2013 REST services.

Happy SharePoint coding!


Saturday, November 15, 2014


SharePoint 2013 has come with various new features; which are really exciting and one of them is REST APIs. REST APIs are very helpful to build client side solutions, you can use them to build a SharePoint App and any client side component. They are very simple and easy to use which helps to speed up the development. You can test them on the browser itself before writing any piece of code.


Main agenda of this blog is to understand how you can use multiple filters in query while fetching List item from list. Though it looks difficult at first look it is very simple to use.

To get items from list you can use following URL :
http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items

For example with above URL(/_api/web/lists/getbytitle('StudentsList')/item) I got  data like below.





Now what if you want to see items having certain values in field? To get only those list items with certain field values you can use filters. You can use filter in REST query like below:

http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items?$filter=[FieldName] eq 'value'.

For example with above URL (/_api/web/lists/getbytitle('StudentsList')/items?$filter=Class eq '1st') I got  data like below.





Now what if you want to apply filter on multiple fields? You will certainly think about putting ‘&&’ or ‘AND’ operators between two filters like below:

http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items?$filter=[FieldName1] eq 'value1' AND  [FieldName2] eq 'value2'

OR

http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items?$filter=[FieldName1] eq 'value1' &&  [FieldName2] eq 'value2'

But they are wrong. You cannot construct multiple filter query like above examples, the correct approach to construct multiple filter query is like below:

http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items?$filter=(([FieldName1] eq 'value1') and  ([FieldName2] eq 'value2')).

http://[SiteUrl]/_api/web/lists/getbytitle('ListName')/items?$filter=((([FieldName1] eq 'value1') and  ([FieldName2] eq 'value2')) or([FieldName3] eq 'value3)).

For example with above URL (/_api/web/lists/getbytitle('StudentsList')/items?Select=Name,Class,Age,City&$filter=((Class eq '2nd') and(Age eq '28')))/item) I get  data like below.





Likewise you can add more filters in REST query according to your requirement.

Happy SharePoint coding.