SharePoint list operations using rest api

In this SharePoint rest api tutorial, we will discuss SharePoint list operations using rest api and various list operations using rest api in SharePoint. Let us see examples on:

  • SharePoint rest api create list
  • How to create a list in SharePoint 2013 online using rest api
  • How to update SharePoint list title using Rest API
  • Delete SharePoint list using Rest API
  • How to add item to sharepoint list using rest api
  • How to get sharepoint list items using rest api
  • sharepoint rest api get list items
  • How to display sharepoint list items using rest api in an HTML table
  • How to delete all items from SharePoint list using rest api
  • SharePoint rest api delete list item by id
  • How to display SharePoint list item using AngularJS REST API
  • How to create a column in SharePoint using rest api
  • How to bind sharepoint list items to dropdownlist using rest api
  • SharePoint rest api filter with and condition
  • SharePoint search rest api

SharePoint rest api create list example

Let us check out first how to create list using SharePoint rest api.

Here we will put our HTML and rest API code inside a script editor web part which we will add inside a web part page SharePoint Online.

If you are new to HTML form design then read: How to design an HTML form quickly

Create list using rest api in SharePoint Online

First, let us discuss how we can create a list using rest api in SharePoint online. Here let us take a textbox and a button. We will let the user put list name in the textbox and click on the Submit button which will create the list and give a successful message.

Below is the HTML code.

HTML Code:

<div>
<strong>Enter List Name::</strong>
<input type="text" id="txtListName" />
<input type="button" id="btnSubmitListName" value="Submit" />
</div>
<div id="divCreateListResults"></div>

Rest API code:

Below is the rest api code. Here we are calling the createList() method to create the SharePoint List. In the metadata, we are passing the list name, base list as well as metadata.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmitListName").on("click", function () {
var listName = $("#txtListName").val();
createList(listName);
});
}

function createList(listName) {
var siteUrl = _spPageContextInfo.webAbsoluteUrl+ "/_api/web/lists";
$.ajax({
url: siteUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.List' },
'BaseTemplate': 100,
'Title': listName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded(data) {
$("#divCreateListResults").html(data.d.Title + " successfully created!");
}

function onQueryFailed() {
alert('Error!');
}
</script>

Here once you Save the page, the form will look like below where user can put the list name and click on submit which will create the list.

create list using rest api in sharepoint
create list using rest api in sharepoint online

If you go to the Site Contents page, you can see the list created like below:

create list using rest api in sharepoint online
SharePoint rest api create list

The above example explains, SharePoint rest api create list.

Create a SharePoint List using Rest API

Let us see another way, to create a SharePoint Online list using Rest API.

Below is the full code Rest API code to create a SharePoint list. The code we can add inside a Script editor web part or content editor web part in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'My Test List REST' }),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},

success: onSuccess,
error: onError
});
function onSuccess(data) {
alert(data+ ' List Created');
}

function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Click to Create List"/>

Once the list has been created, you can see from the site content which will look like below:

create list using rest api in sharepoint
create list using rest api in sharepoint

This will help you to create list using rest api in sharepoint online.

Update SharePoint list title using Rest API

Let us see how to update SharePoint list title using Rest API code.

Below Rest API code will help to update list title using rest api, which we can add inside a script editor web part or in a content editor web part in a web part page in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>

$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('My Test List REST')";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.List' }, 'Title': 'My Test List REST-Updated' }),
headers: {
"X-HTTP-Method":"MERGE",
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val(),
"IF-MATCH": "*"
},

success: onSuccess,
error: onError
});
function onSuccess(data) {
alert(data+ ' List Title Updated');
}

function onError(error) {
alert(JSON.stringify(error));
}
});
});

</script>

<input type="button" id="btnClick" value="Update List Title"/>

Once you click on Update List Title, it will update the list title like below:

update list title using rest api in sharepoint online
update list title using rest api in sharepoint online

The above code we can use to update a list title using rest api in SharePoint Online or SharePoint 2013/2016/2019.

Delete SharePoint List using Rest API

Now, we will see how to delete the list using Rest API in SharePoint Online Office 365 or SharePoint 2013/2016/2019.

Here let us take a textbox and a button in HTML form. The user will enter a list name in the textbox and click on the button which will delete the SharePoint list.

Here we will add the HTML and rest API code inside a script editor web part which is there inside a web part page in SharePoint.

HTML Code:

<div>
<strong>Enter the name of the list to delete:</strong>
<input type="text" id="txtListName" />
<input type="button" id="btnSubmitListName" value="Submit" />
</div>
<div id="divDeleteListResults"></div>

Rest API Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmitListName").on("click", function () {
var listName = $("#txtListName").val();
deleteList(listName);
});
}

function deleteList(listName) {
var siteUrl = _spPageContextInfo.webAbsoluteUrl+ "/_api/web/lists/GetByTitle('" + listName + "')";
$.ajax({
url: siteUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"IF-MATCH": "*"
},

success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded() {
$("#divDeleteListResults").html("List successfully deleted!");
}

function onQueryFailed(sender, args) {
alert('Error!');
}
</script>

Once you save the page and refresh the page, the HTML will appear like below and once user gives the list name and click on Submit, it will delete the list.

delete list using rest api in sharepoint
delete SharePoint list using rest api

Now when you go and see the SharePoint Online Site Contents page, the list will not be there.

This is how we can delete a list using rest api in SharePoint online Office 365. I hope you like an example, sharepoint rest api delete list item.

Add item to SharePoint list using rest api

Let us see how to insert item to sharepoint list rest api or an example on SharePoint rest api add item to list.

Now we will discuss, I am going to explain how to insert items into the SharePoint list using REST API.

In Rest API, we have different types of commands for data Insert, Retrieve, Update, Delete. Insert/Update-POST, Retrieve-GET and Delete-DELETE commands. Now for inserting items to list, using “type : POST ” command.

I created a custom SharePoint list, named it as a “MyCompanyEmployeeList”.

In this list , I added new columns like:

  • EmpName (Replace “Title”)
  • Gender(choice (radiobutton)
  • contactNumber
  • Department(choice(dropdown))
  • Address.
SharePoint rest api add item to list

Next, I created an HTML form based on our list column names and named it “InsertItemstoList.html”.

InsertItemstoList.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://onlysharepoint2013.sharepoint.com/sites/DevSite/SiteAssets/InsertItemsToList.js"></script>
<style>
thead {color:green;}
tbody {color:blue;}
</style>

</head>
<body>
<table border="1"><thead><tr>
<th style="text-align:center" colspan="2">Employee Form</th></tr>
<tr>
</thead>
<tbody>
<td>
<label for="EmpName">EmployeeName</Label>
</td>
<td>
<input type="text" name="EmployeeName" id="txtEmployeeName"></input>
</td>
</tr>
<tr>
<td>
<label for="Gender">Gender</Label>
</td>
<td>
<input type="radio" name="gender" id="radbtnMale" value="Male">Male</input>
<input type="radio" name="gender" id="radbtnFeMale" value="Female">Female</input>
</td>
</tr>
<tr>
<td>
<label for="ContactNumber">ContactNumber</Label>
</td>
<td>
<input type="text" name="ContactNumber" id="txtContactNumber"></input>
</td>
</tr>
<tr>
<td>
<label for="Department">Department</Label>
</td>
<td>
<Select id="selectOption">
<option value="IT">IT</option>
<option value="Finance">Finance</option>
</Select>
</td>
</tr>
<tr>
<td>
<label for="Address">Address</Label>
</td>
<td>
<textarea col="30" rows="4" id="txtAddress"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button  name="Insert" id="btnInsert" value="Insert">Insert</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

InsertItemsToList.js:

Below is the Rest API code to insert items to SharePoint Onnline list.

$(function () {$("#btnInsert").click(function () {InsertListItem();});});
function InsertListItem()
{
var empname  = $("#txtEmployeeName").val();
var gender = $("input[name='gender']:checked").val();
var number = $("#txtContactNumber").val();
var department=$("#selectOption option:selected").val();
var address = $("#txtAddress").val();
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('MyCompanyEmployeeList')/items",
type: "POST",
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.MyCompanyEmployeeListListItem"
},
Title : empname,
Gender: gender,
ContactNumber: number,
Department: department,
Address: address
}),
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "POST"
},
success: function(data, status, xhr)
{
alert("item added sucessfully");
},
error: function(xhr, status, error)
{
alert(JSON.stringify(error));
}
});
}

Now upload these two html and js files in “Site Assets”. Next create a web part page and open this web part page.

For adding content editor web part in that page go to page tab, there click on edit page now the page is in edit mode, here click on add a web part, it will show some categories list.in that go to media content->select content editor web part, next click on add button.then webpart is add on a web part page.

Next click on the Edit Web Part property of the content editor web part, it will show property dialogue box.

In Content Link add your HTML file URL like “/sites/DevSite/SiteAssets/InsertItemsToList.html” and next click on Apply. Now your HTML form is added to your web part page.

sharepoint api add item to list

Now enter values in the form and click on Insert button then item will be added in our list.

rest api add item to list

Now item is added into the list as shown below.

add item to sharepoint list using rest api

This is how we can add item to sharepoint list using rest api or create item in sharepoint list using rest api.

Get sharepoint list items using rest api

Let us see, how to get sharepoint list items using rest API. Now I am going to explain how to retrieve items from a SharePoint Online list using Rest API.

I have created a list, named it as a “MyCompanyEmployeeList” and add items to list as shown below.

get sharepoint list items using rest api

RetriveListUsingRestAPI.js

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input type="button" id="btnClick" value="Get all List Items"/>
<div id="ResultDiv"></div>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyCompanyEmployeeList')/items";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},success: onSuccess,error: onError});function onSuccess(data) {$("#ResultDiv").empty();
var items = data.d.results;
for (var i = 0; i < items.length; i++) {
$("#ResultDiv").append(items[i].Id+ " : " + items[i].Title + '<br />');
}
}
function onError(error) {alert(JSON.stringify(error));
}
});
});
</script>

Create and open a SharePoint web part page. For adding the Script editor web part, in that page go to page tab, there click on edit page now the page is in edit mode, here click on add a web part, it will show some categories list.

On that go to media content -> select Script Editor web part, next click on add button, then web part is added on the web part page.

Copy and Paste the above code in the Script Editor web part and next click on Stop Editing .now click on the Button called “Get all List Items” it display id and title from the SharePoint list.

Now, you can see the result like below:

get sharepoint list items using rest api

This is how to get list items from SharePoint Online list using Rest API.

SharePoint rest api get list items

Let us check out an example on sharepoint rest api get list items.

Now, we will see how to retrieve list items using Rest API in SharePoint Online Office 365. The same code will work fine in both SharePoint 2016 as well as SharePoint 2013 or SharePoint 2019.

Here we will use a button and on button click, we will display sharepoint list items using rest api. We will add the HTML and rest API code inside a script editor web part which we will add inside a web part page.

HTML Code:

<div>
<input type="button" id="btnSubmit" value="Get List Data using Rest API" />
</div>
<div id="divResults"></div>

Rest API Code:

Below is the full rest API code to retrieve SharePoint list item.

Here also we have used _spPageContextInfo.webAbsoluteUrl to get the absolute URL of the site which we have used in the Rest endpoint. You can check out _spPageContextInfo javascript or jquery variable in SharePoint 2013 for more information how we can use _spPageContextInfo.

Then in onQuerySucceeded method, we are retrieving all the lists in for each loop. And we are binding the data into the <div id=”divResults”></div>.

Here we are trying to retrieve SharePoint list items from MyCompanyInfo list which has two columns

  • Title
  • Industry

To retrieve all list item we are building the rest api endpoint URL like below:

var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyCompanyInfo')/items";

Similarly, if you want to retrieve based filter conditions, you can build URL like below, here it will retrieve items whose id is greater than 3.

var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/items?$filter=Id ge 3″;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$("#btnSubmit").on("click", function () {
getListData();
});
});

function getListData() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyCompanyInfo')/items";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded(data) {
var listItemInfo = ";
$.each(data.d.results, function (key, value) {
listItemInfo += '<b>Title:</b> ' + value.Title + ' – <b>Industry:</b> ' + value.Industry + '<br />';
});
$("#divResults").html(listItemInfo);
}
function onQueryFailed() {
alert('Error!');
}

</script>

Once you Save the code and click on the button, it will display all the items from the MyCompanyInfo list.

get sharepoint list items using rest api
display sharepoint list items using rest api

This is how to get sharepoint list items using rest api.

Display sharepoint list items using rest api in an HTML table

Now we will see how to display list data in a grid using Rest API in SharePoint Online or SharePoint 2013/2016.

Here I have a SharePoint list known as Employee which has 4 columns as:

  • Title
  • FirstName
  • LastName
  • Deptname

We have added a few items to the SharePoint list.

Below is the Rest API code which I have put inside a script editor web part in a SharePoint web part page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employees')/items";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="tableEmployee" style="width:100%" border="1 px"><thead><tr><td>Title</td>' + '<td>FirstName</td>' + '<td>LastName</td>' + '<td>Department Name</td>' + '</tr></thead><tbody>';

for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title+ '</td>';
tableContent += '<td>' + objItems[i].FirstName + '</td>';
tableContent += '<td>' + objItems[i].LastName + '</td>';
tableContent += '<td>' + objItems[i].deptname + '</td>';
tableContent += '</tr>';
}
$('#employeeGrid').append(tableContent);
}

function onError(error) {
alert('Error');
}
});
});
</script>

<input type="button" id="btnClick" value="Get Employee Records"/>
<div id="CustomerPanel">
<table id='tableEmployee' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="employeeGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>

Once you click on the button it will display the records like below:

display sharepoint list data in html table using rest api
display sharepoint list items using rest api in an HTML table

This is how we can display sharepoint list items using rest api in an HTML table in SharePoint Online as well as SharePoint 2013/2016/2019. This is an example on display sharepoint list data in html table using rest api.

Delete all items from SharePoint list using rest api

Let us see, how to delete all items from a SharePoint Online list using Rest API.

We can delete all items from SharePoint online list using Rest API. I have a list that has few items inside the list in my SharePoint online site. The list looks like below:

delete item from sharepoint list using rest api
delete item from sharepoint list using rest api

Below is the code which we can add into a script editor web part which we can add in a web part page in SharePoint Online or SharePoint 2013/2016.

Here is the first function we are getting the items and then we are building the rest API URL for deleting an item and passing it to the deleteItem(URL) method.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<input type="button" id="btnDeleteAllItems" value="Delete All Items" />

<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnDeleteAllItems").on("click", function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(‘Announcements’)/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
var items = data.d.results;
$.each(data.d.results, function (key, value) {
var id=value.ID;
var url = "/_api/Web/Lists/getByTitle(‘Announcements’)/getItemById("+id+")";
deleteItem(url);
});
},
error: function (error) {
alert(JSON.stringify(error));
}
});
});
}

function deleteItem(url) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "DELETE",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": "*"
},
success: function (data) {
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
</script>

Once you save the page and click on the button, it will delete all items from the SharePoint Announcements list.

SharePoint rest api delete list item by id

Now we will see how we can delete items from SharePoint list using Rest API in SharePoint Online Office 365. Here we will delete list item based on list item id using Rest API in SharePoint.

Here let us take a textbox where the user can put the item id in the textbox. On submit button, the item will get deleted from the list.

All the HTML code and Rest API code we will put inside a script editor web part inside a SharePoint web part page.

Here we have a list name as MyCompanyInfo which has one item and whose ID is 2.

sharepoint rest api delete list item by id
sharepoint rest api delete list item by id
<div>
Enter ID to Delete:
<input type="text" id="txtId" />
</div>
<div>
<input id="btnSubmit" type="button" value="Submit" />
</div>
<div id="divResult"></div>

Rest API Code:
Here we have can retrieve the item id from the textbox.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
deleteListItem();
});
}

function deleteListItem() {
var id = $("#txtId").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/items(" + id + ")";
$.ajax({
url: fullUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"IF-MATCH": "*"
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded(sender, args) {
$("#divResult").html("Item successfully deleted!");
}

function onQueryFailed() {
alert('Error!');
}
</script>

Once you Save the page, it will display like below. Once user put the item id and click on Submit button it will delete the list item and it will display the successful message.

sharepoint rest api delete all list items
sharepoint rest api delete all list items

Now if you will check the list, you will not find the item inside the list like below:

sharepoint rest api delete list item by id
sharepoint rest api delete list item by id

This is how we can delete list item by id using Rest API in SharePoint Online Office 365.

Display SharePoint list item using AngularJS REST API

Let us see, how to display list items using AngularJS with Rest API in SharePoint Online or SharePoint On-premise.

Here I have an announcement list where I have a few items in my SharePoint Online site. The below code will work in both On-premise as well as Online versions of SharePoint.

Below code you can put inside a script editor web part in web part page in SharePoint Online/2013/2016.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js”></script>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js”></script>
<script src=”http://code.jquery.com/ui/1.10.3/jquery-ui.min.js”></script>

<div ng-app=”listApp”>
<div id=”App1″ ng-controller=”controller1″>
<h1>Team Announcements</h1>
<ul>
<div ng-repeat=”item in items”>
<p><li>{{item.Title}}</li></p>
</div>
</ul>
</div>


<script>

var appVar = angular.module(‘listApp’, []);
appVar.controller(“controller1”, function($scope){
GetListItems($scope, “Training%20Announcements”);
});

function GetListItems($scope, listName){
$.ajax({
url: “/_api/web/lists/GetByTitle(‘”+listName+”‘)/items”,
method: “GET”,
async: false,
headers: { “Accept”: “application/json;odata=verbose” },
success: function(data){
$scope.items = data.d.results;
},
error: function(sender,args){
console.log(args.get_message());
}
});
}

</script>

After you save the page the items from announcement lists will be appear like below:

Display SharePoint list item using AngularJS REST API SharePoint online
Display SharePoint list item using AngularJS REST API SharePoint online

This is how to retrieve the SharePoint Online list item using AngularJs Rest API in SharePoint Online/2013/2016/2019.

SharePoint rest api create column

Let us see how to create a column in a list using Rest API in SharePoint Online or SharePoint 2013/2016/2019.

Here in this demo let us take one textbox and one button in HTML form. The user can give a column name in the textbox and click on the Submit button. Once the column created successfully it will display a successful message in the div whose id is “divResults“.

For this particular example, let us use a script editor web part inside a web part page in SharePoint. In that script editor page, you can add the HTML code as well as the rest API code.

HTML Code:

Below is the HTML code

<div>
<strong>Enter Column Name:</strong>
<input type="text" id="txtColumnName" />
<input type="button" id="btnSubmit" value="Create Column" />
</div>
<div id="divResults"></div>

Rest API Code:

Below is the rest api code to create a column in a SharePoint Online list.

Here is the data, we are passing the metadata for the column, like, Title for the column, and also we are providing the column type by using the FieldTypeKind property. This property gets or sets a value that specifies the type of the field.

  • FieldTypeKind : 1 -> integer value
  • FieldTypeKind : 2 -> single line of text
  • FieldTypeKind : 3 -> multiple lines of text etc.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createColumn();
});
}

function createColumn() {
var folderName = $("#txtColumnName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/Fields";
$.ajax({
url: fullUrl,
type: "POST",
data: "{ '__metadata': { 'type': 'SP.Field' }, 'Title':'" + folderName + "', 'FieldTypeKind': 3 }",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded() {
$("#divResults").html("Column Created Successfully !!!");
}

function onQueryFailed() {
alert('Error!');
}

</script>

Now when we Save the page and refresh the page, the HTML will come. Give a name for the column and click on the button, which will successfully create the column in the list.

create column in list using rest api sharepoint
sharepoint rest api create column

Now if you can navigate to the list settings page, you can see the new column has been added to the list like below:

create column in list using rest api sharepoint online
sharepoint rest api create column

How to get count of items in sharepoint list using rest api

Let us see the code on how to get count of items in sharepoint list using rest api.

We will see how we to get SharePoint list item count using Rest API in SharePoint Online/2013. You can put the below code in a script editor web part or content editor web part.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘MyTestList’)/items";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var itemsCount = data.d.results.length;
alert (itemsCount);
}

function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Count List Items"/>

Once you execute the code, it will give you the count of items in sharepoint list using rest api.

Bind sharepoint list items to dropdownlist using rest api

Now let us see, how to bind sharepoint list items to dropdownlist using rest api.

SharePoint 2013/2016/Online has greatly expanded the REST services available to developers. With this, we have much more SharePoint functionality exposed via CSOM and Web Services.

Also, all of the new REST Services in SharePoint 2013. SharePoint 2013 was able to provide me with a REST API, I could call with jQuery ajax requests, and this was exactly what I wanted.

Below is the way, we can bind SharePoint list items to dropdown list using rest api in SharePoint 2013.

Let’s start out with our basic get commands in REST. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.

Bind SharePoint list items to dropdownlist using Rest api

In my example, I’m accessing a Custom list(countries) and output the result binding it to a dynamical dropdown. I have ordered by column in Ascending only. Using SharePoint’s REST API lets us add these filters in our request. The results are given to us as a JSON object, which we can then loop through and insert into a dropdown runtime.

I also used a modular pattern to structure my code. We can generate our REST request. _spPageContextInfo is a SharePoint object that gives us useful information about the page and site we’re on, including the base URL of our site.

After successfully getting our list information, we just need to loop through our data, put it in a dropdown, and then insert into our predefined container element. jQuery helps make this an easy process.

Let’s proceed.

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts” picker area, go to the “Media and Content” category, select the Script Editor Web Part and press the “Add button”.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following.

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function () {
countriesDrpDownBind();
});

function countriesDrpDownBind() {
var listName = "countries";
var url = _spPageContextInfo.webAbsoluteUrl;
getListItems(listName, url, function (data) {
var items = data.d.results;
var inputElement = '<select id="drpcountries"> <option value="">Select</option>';
// Add all the new items

for (var i = 0; i < items.length; i++) {
var itemId = items[i].Title,
itemVal = items[i].Title;
inputElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';
}

inputElement += '</select>';
$('#divisiondrp').append(inputElement);
$("#drpcountries").each(function () {
$('option', this).each(function () {
if ($(this).text() == 'Select') {
$(this).attr('selected', 'selected')
};
});
});

// assign the change event to provide an alert of the selected option value
$('#drpcountries').on('change', function () {
alert($(this).val());
});
}, function (data) {
alert("Ooops, an error occured. Please try again");
});
}

// READ operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails

function getListItems(listName, siteurl, success, failure) {
$.ajax({
url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$orderby=Title asc",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},

error: function (data) {
failure(data);
}
});
}
</script>

Division
<div id="divisiondrp"></div>

Now, you can see the items bind to the SharePoint list items using Rest API and jQuery.

bind sharepoint list items to dropdownlist using rest api

This is how to bind sharepoint list items to the dropdown list using rest api and jQuery. The same Rest API code, we can use to bind sharepoint list items to the dropdown list using rest api and jQuery in SharePoint 2013/2016/2019.

SharePoint rest api filter with and condition

Let us see how to filter SharePoint list items with rest api filter with and condition.

Here I have a SharePoint custom list which 3 columns name as EmpID, FirstName, and Age. We will try to retrieve records whose Age is greater than 30 by using rest api in SharePoint.

sharepoint rest api filter with and condition
sharepoint rest api filter items

We can put the below rest api code inside a script editor web part or content editor web part in SharePoint web part page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employee')/items/?$filter=Age gt 30";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},

success: onSuccess,
error: onError
});

function onSuccess(data) {
var items = data.d.results;
var result=";
for (var i = 0; i < items.length; i++) {
result +=items[i].Id+ " : " + items[i].Title +'\n';
}
alert (result);
}
function onError(error) {

alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Get all List Items based on Condition"/>

The results will come like below:

sharepoint rest api filter list items
sharepoint rest api filter with and condition

Similarly, if you want to retrieve records based on conditions like Age greater than 20 and less than 32

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employee')/items/?$filter=Age gt 20 and Age lt 33";

The results will come like below:

sharepoint rest api filter with and condition
sharepoint 2013 rest api filter list items

Similarly, If you want to filter based on date, then you can write the URL like below:

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employee')/items/?$filter=Created lt '2015-03-22'";

This is an example of, sharepoint rest api filter with and condition.

SharePoint rest api search query example

Let us, how to search in SharePoint using the REST API. This will work for both SharePoint Online as well as with SharePoint On-premises.

In this example, we have an input box where the user can put the search term and when user will click on the button, it will display the result in an alert box. You can also have your own code to display the results in tabular format as well.

Before that lets analyze the REST API URL for Search:

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='SharePoint'

The above will search on the basis of keyword ‘SharePoint’. And the maximum length for the query text allowed is 4096 characters.

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='Title:SharePoint'

The above will search on the basis of keyword ‘SharePoint’ in the Title.

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='SharePoint'&selectproperties='Title,Path'

The above will search for keyword SharePoint and will return Title and Path properties.

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='SharePoint'&selectproperties='Title,Path'&rowlimit=5

The above will search for keyword SharePoint and will return Title and Path properties and it will return top 5 results.

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='SharePoint'&selectproperties='Title,Path'&startrow=11&rowlimit=5

The above will search for keyword SharePoint and will return Title and Path properties and also it will return 5 results starting from 11th.

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='SharePoint'&refiners='filetype'&refinementfilters='filetype:equals("pdf")'

It will search on the keyword SharePoint and will return pdf files only.

But the below code which you can add inside a script editor web part in SharePoint 2013/2016/Online.

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

<script>

$(function(){
$(“#btnClick”).click(function(){
var queryText = $(“#searchBox”).val();
//var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/search/query?querytext=’Title:SharePoint’&selectproperties=’Title,Path’&rowlimit=5′”;
//var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/search/query?querytext='”+queryText+”‘”&selectproperties=’Title,Path’&rowlimit=5′”;
var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/search/query?querytext='”+queryText+”‘&selectproperties=’Title,Path’&rowlimit=5′”;
alert (requestUri);
$.ajax({
url: requestUri,
type: “GET”,
headers: {
“accept”:”application/json; odata=verbose”
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var items = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
if(items.length==0)
{
alert(“Nothing found !!!”);
}
for (var i = 0; i < items.length; i++) {
alert(“Title: ” +items[i].Cells.results[2].Value + ” Path: ” + items[i].Cells.results[3].Value);
}
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
<input type=”text” value=”SharePoint” id=”searchBox” />

<input type=”button” id=”btnClick” value=”Get Search Results”/>

This is an example of sharepoint search rest api.

Here we learned SharePoint list operations using rest API, how to create a SharePoint list using Rest API in SharePoint Online or SharePoint 2013/2016/2019.

  • How to create a list in SharePoint 2013 online using rest api
  • How to update SharePoint list title using Rest API
  • Delete SharePoint list using Rest API
  • How to add an item to sharepoint list using rest api
  • How to get sharepoint list items using rest api
  • sharepoint rest api get list items
  • How to display sharepoint list items using rest api in an HTML table
  • How to delete all items from SharePoint list using rest api
  • SharePoint rest api delete list item by id
  • How to display SharePoint list item using AngularJS REST API
  • How to create a column in SharePoint using rest api
  • Bind sharepoint list items to dropdownlist using rest api
  • How to sharepoint rest api filter with and condition
  • SharePoint search rest API examples
>