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
  • get sharepoint list item attachment programmatically rest api
  • SharePoint rest api add attachment to list item
  • SharePoint rest api add multiple attachments to list item
  • Display SharePoint list item attachments using REST API and jQuery
  • Delete SharePoint List Item attachment using 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="http://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="http://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.

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="http://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="http://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="http://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.

Get sharepoint list item attachment programmatically rest API

In this particular example, I am trying to retrieve attachments from list item whose id is 3.

Put the below code in a script editor web part or inside a content editor web part.

<script src="http://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(3)/AttachmentFiles";
$.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);
if (data) {
$.each(data.d.results, function () {
// do something
alert( this.ServerRelativeUrl);
});
}
}

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

});

</script>

<input type="button" id="btnClick" value="Get Attachments"/>

Once you save the code and click on the button, it will display all the attachments in the alert dialog box in SharePoint Online or SharePoint 2013/2016 or SharePoint server 2019.

SharePoint rest api add attachment to list item

Below is the step by step tutorial on how to upload an attachment to a new item on the list using Rest API in SharePoint 2013 or SharePoint Online.

The below code snippet will show the Personal Details HTML that has been created for the user to insert data into the list. In Html One tag highlighted to facilitate multi-file upload control, I am leveraging “jquery.multifile.js” plugin. If we don’t use that plugin, the user will select only one input file for upload.

<script type="text/javascript" src="/Script/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/Script/jquery-ui.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/Script/jquery.multifile.js"></script>

<span style="font-size: 22.0pt; padding-left: 20px">Personal Details<o:p></o:p></span>
<table align="left" border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" width="0" id="mytable">
<tbody>
<tr>
<td>
<table align="left" border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="">
<tbody>
<tr>
<td style="" valign="top" class="auto-style16">
<h3>Name</h3>
</td>
<td valign="top" style="padding: 9px;" class="auto-style17">
<input type="text" value="" maxlength="255" id="Name" title="Name" style="width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
<tr>
<td class="auto-style16">
<h3>Address</h3>
</td>
<td class="auto-style17">
<input type="text" value="" maxlength="255" id=" Address" title="Address" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15">
<h3>City</h3>
</td>
<td class="auto-style4">
<input type="text" value="" maxlength="255" id=" City " title=" City " style="width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15">
<h3>Contact Number </h3>
</td>
<td class="auto-style5">
<input type="text" value="" maxlength="255" id=" ContactNumber " title="ContactNumber" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><span style="font-family: &quot; segoe ui&quot; ,sans-serif; color: #444444">Click here to attach file</span>
<div class="files" id="attachFilesHolder ">
<input id="file_input" type="file" name="files[]">
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
<div style="text-align: -webkit-center; padding-bottom: 20px; padding-top: 20px; padding-left: 190px">
<input name="SaveItem" style="height: 40px; font-size: 15px;" class="ms-ButtonHeightWidth" id=" NewSaveItem " accesskey="O" onclick="" type="button" value="Click here to submit " target="_self">
</div>
</tbody>
</table>
sharepoint rest api add attachment to list item
sharepoint rest api add attachment to list item

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page, select 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 HTML and/or JavaScript, as shown below.

<script type="text/javascript">
var arraycount = 0;
var fileUploadeCount = 0;
$(document).ready(function ($) {
$(‘#file_input’).multifile();
$("#NewSaveItem").click(function () { formSave() });
});
function formSave() {
var listItem = "";
var fileArray = [];
$("#attachFilesHolder input:file").each(function () {
if ($(this)[0].files[0]) {
fileArray.push({ "Attachment": $(this)[0].files[0] });
}
});

arraycount = fileArray.length;
listItem = {
__metadata: { "type": "SP.Data.BankDetailsListItem" },
"Name": $("input[title=’Name’]").val(),
"Address ": $("input[title=’Address’]").val(),
"City": $("input[title= City]").val(),
"ContactNumber": $("input[title=’ContactNumber’]").val(),
"Files": fileArray
};
createItemparent("BankDetails", filesarray, listItem);
}

function createNewItem(listname, filearray, listItem) {
var dfd = $.Deferred();
var initializePermsCall = PostAjax(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle(‘" + listname + "‘)/items", listItem);
$.when(initializePermsCall).then(function (permData) {
var id = permData.d.Id;
if (filearray.length != 0) {
for (i = 0; i <= filearray.length – 1; i++) {
loopFileUpload(listname, id, filearray, i).then(
function () {
},

function (sender, args) {
console.log("Error uploading");
dfd.reject(sender, args);
}
);
}
}
});
}

function PostAjax(siteurl, listItem) {
return $.ajax({
url: siteurl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(listItem),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
});
}

function loopFileUpload(listName, id, filearray, fileCount) {
var dfd = $.Deferred();
uploadFile(listName, id, filearray[fileCount].Attachment); return dfd.promise();
}

function uploadFile(listname, ID, file) {
var getFileBuffer = function (file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
};

getFileBuffer(file).then(function (buffer) {

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘" + listname + "‘)/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "‘)",
method: ‘POST’,
async: false,
data: buffer,
processData: false,
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
}, success: onAttachmentSucess
});
});

function onAttachmentSucess() {
fileUploadeCount++;
if (arraycount == fileUploadeCount) {
console.log(data + ‘ uploaded successfully’);
}
}
}

</script>

Final Output:

sharepoint rest api add attachment to list item
sharepoint rest api add attachment to list item

This is how to upload multiple files to sharepoint list item using rest api.

SharePoint rest api add multiple attachments to list item

Let us see how to add multiple attachments to list item in SharePoint rest api.

The below code snippet will show the Personal Details HTML that has been created for the user to insert data into the list. In Html One tag highlighted to facilitate multi-file upload control, I am leveraging “jquery.multifile.js” plugin. If we don’t use that plugin, the user will select only one input file for upload.

<script type="text/javascript" src="/Script/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/Script/jquery-ui.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/Script/jquery.multifile.js"></script>
<span style="font-size: 22.0pt; padding-left: 20px">Personal Details<o:p></o:p></span>

<table align="left" border="1″ cellpadding="0″ cellspacing="0″ class="MsoTableGrid" width="0″ id="mytable">
<tbody>
<tr>
<td>
<table align="left" border="1″ cellpadding="0″ cellspacing="0″ class="MsoTableGrid" style="">
<tbody>
<tr>
<td style="" valign="top" class="auto-style16″>
<h3>Name</h3>
</td>
<td valign="top" style="padding: 9px;" class="auto-style17″>
<input type="text" value="" maxlength="255″ id="Name" title="Name" style="width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
<tr>
<td class="auto-style16″>
<h3>Address</h3>
</td>
<td class="auto-style17″>
<input type="text" value="" maxlength="255″ id=" Address" title="Address" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15″>
<h3>City</h3>
</td>

<td class="auto-style4″>
<input type="text" value="" maxlength="255″ id=" City " title=" City " style="width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15″>

<h3>Contact Number </h3>
</td>
<td class="auto-style5″>
<input type="text" value="" maxlength="255″ id=" ContactNumber " title="ContactNumber" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><span style="font-family: &quot; segoe ui&quot; ,sans-serif; color: #444444″>Click here to attach file</span>
<div class="files" id="attachFilesHolder ">
<input id="file_input" type="file" name="files[]">
</div>
</td>
<td></td>
</tr>
</tbody>
</table>

<div style="text-align: -webkit-center; padding-bottom: 20px; padding-top: 20px; padding-left: 190px">
<input name="SaveItem" style="height: 40px; font-size: 15px;" class="ms-ButtonHeightWidth" id=" NewSaveItem " accesskey="O" onclick="" type="button" value="Click here to submit" target="_self">
</div>
</tbody>
</table>
upload multiple attachments to sharepoint list item using rest api
upload multiple attachments to sharepoint list item using rest api

Step-1: Navigate to your SharePoint 2013 site. From this page, select Site Actions -> Edit Page.

Edit the page, go to the Insert tab in the Ribbon, and click on 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-2: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type="text/javascript">
var oLoader;
var attcount = 0;
var arraycount = 0;
$(document).ready(function ($) {
$(‘#file_input’).multifile();//For facilitate multi file upload
$("#NewSaveItem").click(function () { formSave() });
});
function formSave() {
oLoader = SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it", "Creating New Bank Account…");
for (i = 0; i < count; i++) {
var data = [];
var fileArray = [];
$("#attachFilesHolder input:file").each(function () {
if ($(this)[0].files[0]) {
fileArray.push({ "Attachment": $(this)[0].files[0] });
}
});
data.push({
"Name": $("input[title=’Name’]").val(),
" Address ": $("input[title=’Address’]").val(),
"City": $("input[title= City]").val(),
"ContactNumber": $("input[title=’ContactNumber’]").val(),
"Files": fileArray
});
createNewItemWithAttachments("BankDetails", data).then(
function () {
if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);
},
function (sender, args) {
console.log(‘Error occured’ + args.get_message());
}
)
}
}
var createNewItemWithAttachments = function (listName, listValues) {
var fileCountCheck = 0;
var fileNames;
var context = new SP.ClientContext.get_current();
var dfd = $.Deferred();
var targetList = context.get_web().get_lists().getByTitle(listName);
context.load(targetList);
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = targetList.addItem(itemCreateInfo);
listItem.set_item("Name", listValues[0].Name);
listItem.set_item("Address", listValues[0].Address);
listItem.set_item("City", listValues[0].City);
listItem.set_item("ContactNumber", listValues[0].ContactNumber);
listItem.update();
context.executeQueryAsync(
function () {
var id = listItem.get_id();
if (listValues[0].Files.length != 0) {
if (fileCountCheck <= listValues[0].Files.length – 1) {
loopFileUpload(listName, id, listValues, fileCountCheck).then(
function () {
},
function (sender, args) {
console.log("Error uploading");
dfd.reject(sender, args);
}
);
}
}
else {
dfd.resolve(fileCountCheck);
}
},
function (sender, args) {
console.log(‘Error occured’ + args.get_message());
}
);
return dfd.promise();
}
function loopFileUpload(listName, id, listValues, fileCountCheck) {
var dfd = $.Deferred();
uploadFileHolder(listName, id, listValues[0].Files[fileCountCheck].Attachment).then(
function (data) {
var objcontext = new SP.ClientContext();
var targetList = objcontext.get_web().get_lists().getByTitle(listName);
var listItem = targetList.getItemById(id);
objcontext.load(listItem);
objcontext.executeQueryAsync(function () {
console.log("Reload List Item- Success");
fileCountCheck++;
if (fileCountCheck <= listValues[0].Files.length – 1) {
loopFileUpload(listName, id, listValues, fileCountCheck);
} else {
console.log(fileCountCheck + ": Files uploaded");
attcount += fileCountCheck;
if (arraycount == attcount) {
if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);
}
}
},
function (sender, args) {
console.log("Reload List Item- Fail" + args.get_message());
});
},
function (sender, args) {
console.log("Not uploaded");
dfd.reject(sender, args);
}
);
return dfd.promise();
}

function uploadFileHolder(listName, id, file) {
var deferred = $.Deferred();
var fileName = file.name;
getFileBuffer(file).then(
function (buffer) {
var bytes = new Uint8Array(buffer);
var binary = ";
for (var b = 0; b < bytes.length; b++) {
binary += String.fromCharCode(bytes[b]);
}
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
console.log(‘ File size:’ + bytes.length);
$.getScript(scriptbase + "SP.RequestExecutor.js", function () {
var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
createitem.executeAsync({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle(‘" + listName + "‘)/items(" + id + ")/AttachmentFiles/add(FileName=’" + file.name + "‘)",
method: "POST",
binaryStringRequestBody: true,
body: binary,
success: fsucc,
error: ferr,
state: "Update"
});

function fsucc(data) {
console.log(data + ‘ uploaded successfully’);
deferred.resolve(data);
}

function ferr(data) {
console.log(fileName + "not uploaded error");
deferred.reject(data);
}
});
},
function (err) {
deferred.reject(err);
}
);
return deferred.promise();
}

function getFileBuffer(file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
</script>
Rest API upload multiple attachment to list item SharePoint Online
Rest API upload multiple attachment to list item SharePoint Online

This is how we can add multiple attachments in sharepoint list using rest api.

Display SharePoint list item attachments using REST API and jQuery

Let us see how to show the SharePoint list item attachments using REST API and jQuery. We will use Rest API to display list item attachments in SharePoint Online or SharePoint 2013/2016/2019.

Now let’s use some REST API to pull these attachments and display them in list.

For retrieving attachments I am using REST API, URL for all attachments collection can be built like below

{Site URL}/_api/web/lists/getbytitle([List Title])/items([item ID])/AttachmentFiles

I have created a custom list in the host site named “Attachment“. Adding multiple items with attachments and let’s say that we want to show the item level attachments on the item selection.

Display SharePoint list item attachments using REST API
Display SharePoint list item attachments using REST API

I have an item (Item ID: 1) that has the following attachments.

Display SharePoint Online list item attachments using REST API
Display SharePoint Online list item attachments using REST API

I wanted to get the URLs of the list item attachments so that I could use it in my HTML. To fetch the Item ID of the list item and bind to dropdown. Once we have selected any Item ID from the list of Item IDs from Dropdown, the attachments of the respective item are shown. An on-change event is used to fetch and we show the related attachments.

Use the procedure given below.

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page, select 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 HTML and/or JavaScript, as shown below.

<script type="text/javascript" src="../../SiteAssets/Script/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function ($) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments')/items?$select=Id";
getListItems(url, function (data) {
var items = data.d.results;
var SelectElement = '<select id="drpListItem" style="width:100%" name="options"><option value="">Select</option>';

// Add all the Item Id in Dropdown
for (var i = 0; i < items.length; i++) {
var itemId = items[i].Id;
SelectElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';
}

SelectElement += '</select>';
$('#ItemID').append(SelectElement);
// assign the change event
$('#drpListItem').on('change', function () {
if ($(this).val() != "") {
var Requestorurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments')/items(" + $(this).val() + ")/AttachmentFiles";
getListItems(Requestorurl, function (data) {
var results = data.d.results;
var htmlStr = "";
if (data.d.results.length > 0) {
$.each(data.d.results, function () {
if (htmlStr === "") {
htmlStr = "<li><a id='attachment' href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></li>";
}
else {
htmlStr = htmlStr + "<li><a id='attachment' href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></li>";
}
});
}
else { htmlStr = "<strong>There are no attachments to show in this item.<strong>"; }
$('#attachmentsContainer').html(htmlStr);
});
}
});
}, function (data) {
console.log("An error occurred. Please try again.");
});

});

function getListItems(siteurl, success, failure) {
$.ajax({
url: siteurl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},

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

Final Output:

List Item with Attachments:

display sharepoint list item attachments using rest api
display sharepoint list item attachments using rest api

List item without Attachments:

display SharePoint 2013 list item attachments using REST API
display SharePoint 2013 list item attachments using REST API

The above code we can use to display SharePoint list item attachments using REST API and jQuery in SharePoint 2013/2016/2019 or SharePoint Online.

Delete SharePoint List Item attachment using Rest API

Let us discuss, how to delete SharePoint list item attachments using REST API and jQuery in SharePoint 2013/2016/2019 or SharePoint Online.

To remove attachments I am using REST API, to delete only specific attachments (based on the attached file name and list Item) we need to build a URL as shown below:

{SiteURL}/_api/web/lists/GetByTitle([ListTitle])/GetItemById([ItemID])/AttachmentFiles/getByFileName([ FileTitle ])

I have created a custom list named “Attachments” in the host site and have added multiple items with attachments, now let’s say that we want to “Delete” the attachments on any particular item which we want.

delete sharepoint list item attachment using rest api
delete sharepoint list item attachment using rest api

I have an item (Item ID: 1) that has the following attachments.

delete list item attachment using rest api in sharepoint online
delete list item attachment using rest api in sharepoint online

I wanted to get the URLs of the list item attachments with delete option so that I could use it in my html. To fetch the Item ID of the list item and bind to dropdown. Once we have selected any Item ID from the list of Item IDs from Dropdown, the attachments of the respective item are shown. Click on X (Delete icon) to Delete the Attachment on the item.

Below is the step by step tutorial on how to delete SharePoint List Item attachment using Rest API.

Step-1: Navigate to your SharePoint 2013 site.

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

Edit the page, go to the Insert tab in the Ribbon and click 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 HTML and/or JavaScript, as shown below.

<script type="text/javascript" src="../../SiteAssets/Script/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function ($) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments’)/items?$select=Id";
getListItems(url, function (data) {
var items = data.d.results;
var SelectElement = '<select id="drpListItem" style="width:100%" name="options"><option value="">Select</option>’;
// Add all the Item Id in Dropdown
for (var i = 0; i < items.length; i++) {
var itemId = items[i].Id;
SelectElement += '<option value="' + itemId + '"selected>’ + itemId + '</option>’;
}
SelectElement += '</select>’;
$('#ItemID’).append(SelectElement);
// assign the change event
$('#drpListItem’).on('change’, function () {
if ($(this).val() != "") {
var Requestorurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments’)/items(" + $(this).val() + ")/AttachmentFiles";
var ID = $(this).val();
getListItems(Requestorurl, function (data) {
var results = data.d.results;
var htmlattach = "";
if (data.d.results.length > 0) {
$.each(data.d.results, function () {
if (htmlattach === "") {
htmlattach = "<p class=’uploaded_image’> <a href=’javascript:void(0);’ id='" + ID + "' class=’remove’>&times;</a> <span class=’filename’><a id=’attachment’ href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></span></p>";
}
else {
htmlattach = htmlattach + "<p class=’uploaded_image’> <a href=’javascript:void(0);’ id='" + ID + "' class=’remove’>&times;</a> <span class=’filename’><a id=’attachment’ href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></span></p>";
}
});
}
else { htmlattach = "<strong>There are no attachments to in this item.<strong>"; }
$('#attachmentsContainer’).html(htmlattach);
});
}
});
}, function (data) {
console.log("An error occurred. Please try again.");
});
$(document).on("click", "a.remove", function () {
DeleteItemAttachment($(this).attr('id’), $(this).next('span’).text());
$(this).parent().remove();
});
});
function getListItems(siteurl, success, failure) {
$.ajax({
url: siteurl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}

function DeleteItemAttachment(ItemId, FileTitle) {
var Dfd = $.Deferred();
var Url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Attachments’)/GetItemById(" + ItemId + ")/AttachmentFiles/getByFileName('" + FileTitle + "') ";
$.ajax({
url: Url,
type: 'DELETE’,
contentType: 'application/json;odata=verbose’,
headers: {
'X-RequestDigest’: $('#__REQUESTDIGEST’).val(),
'X-HTTP-Method’: 'DELETE’,
'Accept’: 'application/json;odata=verbose’
},

success: function (data) {
Dfd.resolve(data);
},
error: function (error) {
Dfd.reject(JSON.stringify(error));
}
});
return Dfd.promise();
}
</script>

In the below screen shot we have delete “Account.doc” File on click X (Delete icon).

delete list item attachment using rest api in sharepoint
delete list item attachment using rest api in sharepoint

Final Output:

delete sharepoint list item attachment using rest api
delete sharepoint list item attachment using rest api
delete attachments of SharePoint list item using REST API
delete attachments of SharePoint list item using REST API

The above rest api code we can use to delete list item attachments using Rest API in SharePoint 2019/2016/2013 or SharePoint Online.

Add a content type to SharePoint List using Rest API

Let us now see, how to add a SharePoint content type to a list or library using rest api.

In this example let us take a button and click on the button, we will add the reservation content type to a custom list that is there on the site. Both the HTML code and the rest API code let us put inside a script editor web part which is there inside a web part page in SharePoint.

HTML Code:

<div>
<input type="button" id="btnSubmit" value="Add Content Type to List" />
</div>
<div id="divResults"></div>

Rest API Code:

Here if you will look at the code, we are adding a content type id like below:
“contentTypeId”: “0x0102004F51EFDEA49C49668EF9C6744C8CF87D”

In this particular example, the ID is the id of a reservation content type. To get any content type id, you can go to the site settings -> then Site Content Type. Then you can click on any of the content type and from the browser, you can get the content type id. You will see like below:

?ctype=0x0102004F51EFDEA49C49668EF9C6744C8CF87D

Below is the full rest api code.

<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 () {
addContentType();
});
}

function addContentType() {
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('MyCompanyInfo')/ContentTypes/AddAvailableContentType";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
"contentTypeId": "0x0102004F51EFDEA49C49668EF9C6744C8CF87D"
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded() {
$("#divResults").html("Content Type Added Successfully to List !!!");
}

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

Once you Save the web part page, you can see a button will appear and on button click, it will add the particular content type to the list which looks like below:

add content type to sharepoint list using rest api

Now if you will open the SharePoint Online list, you can see the content type like below:

add content type to sharepoint online list using rest api

Here we learned, how to add an existing content type to a custom list in SharePoint Online using Rest API. We can also use the same code to add a content type to SharePoint list using Rest API in SharePoint 2013/2016.

You may also like the following rest API articles:

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
  • SharePoint rest api add an attachment to list item
  • SharePoint rest api add multiple attachments to list item
  • Display SharePoint list item attachments using REST API and jQuery
  • Delete SharePoint List Item attachment using Rest API
>