SharePoint Rest API Tutorial and Examples

In this SharePoint rest api tutorial and examples article, we will discuss how to work with SharePoint rest API, advantages of rest api in SharePoint 2013/2016/Online. Also, we will discuss how SharePoint REST API works, various SharePoint Rest API HTTP commands, various properties of SharePoint Rest API, and also we will see various SharePoint Online rest api examples.

The Rest API SharePoint Online code whatever we will use in this tutorial will work in SharePoint Online as well as SharePoint 2013/2016/2019.

At A Glance - Here's what we'll cover: show

SharePoint Rest API

We worked on various client object model techniques like CSOM, JSOM, etc. Microsoft also introduced REST (Representational State Transfer) service in SharePoint 2013 which is comparable to existing SharePoint client object models.

By using Rest API, we can interact with SharePoint remotely. We can interact to with SharePoint data by using any technology that supports REST web requests like you can perform create, read, update and delete operations from apps for SharePoint, client applications, etc. using REST technologies.

How SharePoint REST API works

In SharePoint 2013/2016/Online you can interact remotely with SharePoint sites using REST API. You will be able to interact by using any technology that supports REST web requests. You need to construct a RESTful HTTP request, using the Open Data Protocol (OData) standard.

To access SharePoint resources using REST, construct a RESTful HTTP request, using the Open Data Protocol (OData) standard, which corresponds to the desired client object model API.

Example:
Here is below the client object model and SharePoint 2013 REST API end point:

Client object model method:
List.GetByTitle(listname)

REST endpoint:
http://server/site/_api/lists/getbytitle(‘listname’)

Similarly if you want to retrieve all the items from a SharePoint list, you will use the below CSOM code.

var items = List.GetByTitle("Employees").GetItems();

If you want to retrieve the same list items using Rest API in SharePoint 2013, you have to construct the Rest endpoint URL:

https://{site_url}/_api/lists/getbytitle('Employees')/items

Example:

https://tsinfo.sharepoint.com/sites/enjoysharepoint/_api/lists/getbytitle('Employees')/items
sharepoint 2013 rest api
SharePoint rest api tutorial and examples

Here your application will send an HTTP request and client.svc web service handles the request which internally calls the Server object model to retrieve data from the Content database.

And then it sends the response in either Atom or JavaScript Object Notation (JSON) format which your client application should able to parse.

REST is a software architecture that uses uniform resource identifiers (URIs) to specify operations against a remote service.

Open Data Protocol (OData) is the protocol that is used along with REST to access many cloud-based services.

Suppose in the client object model we write List.GetByTitle(listname) to retrieve a particular list. The same thing if you want to do in REST then it will be like:

https://server/site/_api/lists/getbytitle('listname')

This is known as REST endpoint.

SharePoint Rest API HTTP commands

If you want to do some CRUD operations in SharePoint using Rest API like adding items to a list, deleting items from a list, or updating items in the SharePoint list, we have to build the Rest endpoints.

To build the SharePoint 2013 Rest API endpoints we need to use the HTTP requests like below:

  • If you want to read data from the SharePoint site then you should use HTTP GET request. Example: reading list items
  • Similarly, if you want to add or update then you should use an HTTP POST request. Example: Create a list or library
  • If you want to update an existing resource you can use the HTTP PUT request. Example: Update a list or library Title or Description
  • If you want to Delete then you should do an HTTP DELETE request. Example: Delete a SharePoint List or Library

HTTP operations in SharePoint 2013 REST services

The endpoints in the SharePoint 2013 REST service correspond to the types and members in the SharePoint client object models.

By using HTTP requests, you can use these REST endpoints to perform typical CRUD (Create, Read, Update, and Delete) operations against SharePoint entities, such as lists and sites.

Typically, endpoints that represent Read operations map to HTTP GET commands. Endpoints that represent update operations map to HTTP POST commands, and endpoints that represent update or insert operations map to HTTP PUT commands.

In SharePoint 2013, use POST to create entities such as lists and sites. The SharePoint 2013 REST service supports sending POST commands that include object definitions to endpoints that represent collections.

For example, you could send a POST command that included a new list object definition in ATOM to the following URL, to create a SharePoint list:

https://<site url>/_api/web/lists

For POST operations, any properties that are not required are set to their default values. If you attempt to set a read-only property as part of a POST operation, the service returns an exception.

Use PUT and MERGE operations to update existing SharePoint objects. Any service endpoint that represents an object property set operation supports both PUT requests and MERGE requests.

For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property.

For PUT commands, however, any properties you do not explicitly set are set to their default properties. In addition, if you do not specify all required properties in object updates when using HTTP PUT commands, the REST service returns an exception.

Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object represented by that endpoint. In the case of recyclable objects, such as lists, files, and list items, this results in a Recycle operation.

To access a specific SharePoint site collection using Rest API, you can use like below:

 https://server/site/_api/site

To access a specific SharePoint site in Rest API, you can use like below:

https://server/site/_api/web

SharePoint 2013 REST endpoints examples

Here are a few rest endpoints for SharePoint 2013/2016/Online. The REST interface exposes all of the SharePoint entities and operations that are available in the other SharePoint client APIs.

One advantage of using REST is that you don’t have to add references to any SharePoint libraries or client assemblies. Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as webs, lists, and list items.

Here we will see the different areas, what is corresponding client object model, corresponding REST EndPoint, and the Server Object Model.

List

  • Client Object Model: ClientContext.Web.Lists
  • REST EndPoint: https://server/site/_api/web/lists
  • Server Object Model: SPList

Site

  • Client Object Model: ClientContext.Site
  • REST EndPoint: https://server/site/_api/site
  • Server Object Model: SPSite

Web

  • Client Object Model: ClientContext.Web
  • REST EndPoint: https://server/site/_api/web

User Profile

  • Client Object Model: ClientContext.Web.Lists
  • REST EndPoint: https://server/site/_api/Sp.UserProfiles.PeopleManager

Search

  • Client Object Model: ClientContext.Web.Lists
  • REST EndPoint: https://server/site/_api/search

Publishing

  • Client Object Model: ClientContext.Web.Lists
  • REST EndPoint: https://server/site/_api/publishing

A few more SharePoint Rest API end point examples:

  • https://{site url}/_api/web/title : Get the title of the web or site
  • https://{site url}/_api/lists : Retrieve all the lists and libraries presented on the SharePoint site
  • https://{site url}/_api/lists/getbytitle(‘listname’)/items: Retrieve all the items from a particular list
  • https://{site url}/_api/lists/getbytitle(‘listname’)?select=Title : Retrieve Title of the SharePoint list

Advantages of using rest api in SharePoint

The advantages of using REST is that you don’t have to add references to any SharePoint 2013 libraries or client assemblies. Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as webs, lists, and list items.

In jsom, SP.js files need to be loaded before the code execution, but in Rest API no such .js files are required.

Another advantages of Rest API in SharePoint is that, Rest API is easier to work and even you can use the browser to see the result and to test them.

How to get and send the form digest value

If you are doing a POST request in Rest API in SharePoint, then you need to pass the form digest value in the X-RequestDigest header. Even if you are using the Rest API code in a script editor web part or if you are using it in a SharePoint Add-in, you need to

You can do this by writing the below lines of code:

"X-RequestDigest": $("#__REQUESTDIGEST").val()

SharePoint Rest API Examples

Below are few examples of SharePoint Rest API. These SharePoint 2013 rest api examples will help you to work with SharePoint 2013/Online/2016

Retrieve user display name using Rest API in SharePoint Online/2013

In the first SharePoint 2013 rest api example, we will see how to get a user display name using Rest API in SharePoint.

Below is the SharePoint 2013 Rest API code to retrieve the user display name using Rest API in SharePoint Online.

Here I on a button click I am displaying the display name of the logged in user in SharePoint using Rest API.

<input type="button" id="btnClick" value="Click Here"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <script>
$(function(){
$("#btnClick").click(function(){
var userid = _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept": "application/json;odata=verbose" };  
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,        
error: onError    
}); 
function onSuccess(data, request) {        
var userinfo = data.d;               
alert ('Display Name: '+ userinfo.Title);  
} 
function onError(error) {        
alert("error");    
}
});
}); 
</script>

Here Title property displays the user display name, similarly, you can use the Email property to retrieve the Email ID of the logged user and you can also use the LoginName property to retrieve the user’s login name in SharePoint Online or SharePoint 2013/2016.

Delete SharePoint 2013/Online list Item using REST API

In this SharePoint Rest API example, we will see how we can delete a SharePoint 2013 list item using REST API. If you want to do SharePoint operation without using server-side code then Rest API is very much useful.

Here I have a button in a web part page and when user clicks on that button, the list item will get deleted.

Copy the below code and paste inside a script editor web part. Here we are retrieving the list item by using the getItemById method.

Here you will see there are 3 items in the list like below and by using REST API we will delete the 2nd item from the list.

sharepoint 2013 rest api
sharepoint 2013 rest api delete all list items
<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('BijayTestList')/getItemById(2)";
$.ajax({
url: requestUri,
type: "DELETE",
headers: {
"accept":"application/json",
"X-RequestDigest":$("#_REQUESTDIGEST").val(),
"IF-MATCH":"*"
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
alert(data+ ‘ Item Deleted’);
}
function onError
(error) {
alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Click Here"/>

Now you can see the list will have only two items in the SharePoint Online list.

sharepoint 2013 rest api example
sharepoint 2013 rest api delete list item

This is how to delete list item using Rest API in SharePoint Online or SharePoint 2013/2016.

Delete SharePoint 2013/Online list using REST API

In this SharePoint 2013 Rest API example, we will discuss how we can delete a SharePoint 2013/Online list using the REST API. In SharePoint 2013/2016/Online you can use the REST API to do lots of operations.

Here I have a button in a web part page and when a user clicks on that button, the SharePoint list will get deleted.

Copy the below code and paste inside a script editor web part. Here we are retrieving the list by using the getByTitle method.

<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('Columns_List')";
$.ajax({
url: requestUri,
type: "DELETE",
headers: {
"accept":"application/json",
"X-RequestDigest":$("#_REQUESTDIGEST").val(),
"IF-MATCH":"*"
},

success: onSuccess,
error: onError
});

function onSuccess(data) {
alert('List Deleted');
}
function onError
(error) {
alert(error);
}
});
});
</script>

<input type="button" id="btnClick" value="Click Here"/>

This way we can delete a list using Rest API in SharePoint Online or SharePoint 2013/2016.

get alternate languages from language settings in SharePoint using Rest API

This SharePoint Rest API tutorial explains, how to retrieve alternative languages using Rest API in SharePoint Online. You can see the alternative language from Site settings -> then Language Settings which is under “Site Administration” section.

sharepoint online rest api sample code
get alternate languages using SharePoint rest api

Below is the full code which I have put in a script editor web part inside a SharePoint web part page. You can use the code according to your requirement.

<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/supportedUILanguageIds";
$.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 value = data.d.SupportedUILanguageIds.results;
alert(value);
for (var i=0; i<value.length; i++) {
alert(value[i]);
}
}

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

<input type="button" id="btnClick" value="Get AlternateLanguages"/>
sharepoint 2013 rest api example
sharepoint 2013 rest api example

This is how we can get alternate languages from language settings in SharePoint Online or SharePoint 2013/2016 using Rest API.

Retrieve all lists and libraries using Rest API in SharePoint

This Rest API example explains, how to retrieve all lists and libraries using Rest API in SharePoint Online Office 365 or in SharePoint 2013/2016.

Here we will take a button and on click of the button, we will display all lists. Both the HTML code and the rest API code we will put inside a script editor web part which we will add inside a web part page.

Below is the HTML Code:

<div>
<input type="button" id="btnSubmit" value="Get All Lists" />
</div>
<div id="divResults"></div>
<div id="divAllLists"></div>

Rest API Code:

Here we have first given the jQuery reference. If you are new to jQuery you can check out this article to know Load the Data in JQuery DataTable from SharePoint 2013 List using REST API.

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=”divAllLists”></div>

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

function getAllLists() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists";
$.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 += 'Title: ' + value.Title + '<br />';
});
$("#divAllLists").html(listItemInfo);
}
function onQueryFailed() {
alert('Error!');
}
</script>

Once you Save the code and click on the button, it will display all the lists and libraries from the SharePoint site.

sharepoint online rest api tutorial
Get SharePoint lists using Rest API

Retrieve Rich Textbox content as plain text using REST API SharePoint 2013

Now we will see how to retrieve Rich textbox content as plain text without HTML tags using REST API in SharePoint 2013.

In SharePoint 2013/2016 or SharePoint Online, I have a list which has a list item that contains a rich textbox field. I want to retrieve that content as plain text using Rest API.

By default my rich textbox content looks like below:

sharepoint 2016 rest api tutorial
sharepoint 2016 rest api tutorial

Insert the below code inside and Script editor web part. Then click on the button, you will able to see the result in an alert box.

<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('MyTest')/getitembyid(1)";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});

function onSuccess(data, request) {
var listiteminfo = data.d;
alert('Content: '+ listiteminfo.Description);
var pageContentText = $(listiteminfo.Description).text();
alert (pageContentText);
}

function onError(error) {
alert("error");
}

});
});

</script>

<input type="button" id="btnClick" value="Click Here"/>

After that the result will appear like below:

sharepoint online rest api tutorial
sharepoint online rest api tutorial

This is how we can retrieve Rich Textbox content as plain text using REST API SharePoint 2013/2016 or SharePoint Online.

SharePoint Rest API filter

Scenario:
In old days working with SharePoint lists or library, many times we came across querying lists and applying filter on list items using CAML Query. We all know constructing long CAML query gets confusing and many lines of chunks as well.

But no worries REST is the life saver; with REST it’s very easy to filter lists and gives to flexibility using few lines or sometimes just one line of code.

In this post, I will be showing how you can use REST to filter or query on SharePoint lists and returns data as you want.

You’ll first start to craft your URI like the following:

https://<siteUrl>/_api/Web/Lists/GetByTitle(‘listname’)/items?$select*&$filter= Title eq ‘test’
  • $Select: Lets you select list columns you want to return
  • $filter: Condition based results.

Refer to the following images and code for clear understanding.

SharePoint Rest API Tutorial
SharePoint Rest API Tutorial

Rest API Query Filter in SharePoint

1st Approach:

Open the browser and add the following URL in the address bar:

https://hostssite/apps/TestAppsite/_api/Web/Lists/GetByTitle(‘Divisions’)/items?$select=*&$filter=Title eq ‘test1’
sharepoint 2013 rest api filter
SharePoint Rest API Tutorial

2nd Approach: using jquery

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”dialogue, go to the “Media and Content” category, select the “Script Editor” Web Part and click 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 code snippet:

function Divsion ()
{
var listName = "Divisions";
var itemId="";
var Ownurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘ Divisions’)/items?$select=OwnerEmailID&$filter=Title eq ‘test1′";
$.ajax({ 
url: Ownurl,
headers: { Accept: "application/json;odata=verbose" },
async:false,
success: function (data) {
var items = data.d.results;
if (items[0].OwnerEmailID != "") {
itemId = items[0].OwnerEmailID;
}

},eror: function (data) {
alert("An error occurred. Please try again.");
}
});
}

Set default value to a field in a list using Rest API in SharePoint Online

Let us see how to set a default value to a field in a list using Rest API in SharePoint Online. As a developer, we should learn about SharePoint client-side development.

Set default value to a field in a list using Rest API in SharePoint

I am doing this demo in a SharePoint Online site, but you can use your on-premise site also.

Here I have a custom list name as MyChartList and in that list in SharePoint. I have a column name as MyDefaultValueColumn in the same list. In the MyDefaultValueColumn I have set a default value as Hiii like below:

Set default value to a field in a list using Rest API in SharePoint
Set default value to a field in a list using Rest API in SharePoint Online

Then I have added Rest API code inside a script editor web part in a web part page and then added the below code inside the script editor web part in the web part page to 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('MyChartList')/fields/getbytitle('MyDefaultValueColumn')";
$.ajax({
url: requestUri,
type: "POST",
data: "{ '__metadata': { 'type':'SP.Field' }, 'DefaultValue': 'Hello Updated Value' }",
headers: {
"Accept":"application/json;odata=verbose",
"X-HTTP-Method":"MERGE",
"content-type":"application/json;odata=verbose",
"X-RequestDigest":$('#__REQUESTDIGEST').val(),
"If-Match": "*",
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
alert('Success');
}

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

<input type="button" id="btnClick" value="Update Default Column Value"/>

Here Once user click on the button, then the Default value will be updated with “Hello Updated Value” which we have set inside the code. And now if you will check the default value for the particular column it will look like below:

Set default value to a field in a list using Rest API in SharePoint Online
Set default value to a field in a list using Rest API in SharePoint Online

SharePoint Online add top navigation link using Rest API

Now, let us see how to add a top navigation link using Rest API in SharePoint Online. This solution is provided by our EnjoySharePoint author Akash Kumhar.

Let us demonstrate this by using a little JQuery and REST API to add a link in the Top Navigation which makes it a custom top navigation link since we are using some code to achieve it.

Prerequisites:
REST API TopNavigationbar EndPoint to use in Add_ins – /_api/web/navigation/TopNavigationbar

Scenario:
Now, I have created a site that has just the site name for the top navigation which navigates to the Home page by default.

Add Top Navigation Link to a SharePoint Site Using REST API
SharePoint 2013 Add Top Navigation Link to a Site Using REST API

So, let’s say we are adding a custom navigation link for the Top Navigation i.e. “AnotherPage”.

Add Top Navigation Link to a SharePoint Site Using REST API

Implementation:
We will achieve this by adding a link to the top navigation bar on a button click. Please follow the step by step procedure for the same.

Step-1:
Open your SharePoint 2013 site. Now you are possibly on the home page, Go to Site Actions > Edit Page.

Once the Page is in Edit mode, add a Script Editor Web Part to the page.

To add a Script Editor Web Part, click “Web Part” option under the “Insert” tab on the ribbon. In the Categories section click “Media and Content”, select the “Script Editor” Web Part in the adjacent window, and click “Add” button.

Step-2:
Once the Web Part is inserted into the page, edit the Web Part and then “EDIT SNIPPET”. Insert the HTML and/or JavaScript, as shown below.

Add Top Navigation Link to a Site Using REST API in SharePoint 2013:

<input type="button" value="Add Top Navigation Link" id="createTopNav"></input>

<script type="text/javascript" src="../../SiteAssets/1.11.2.jquery.js"></script>

<script type="text/javascript">
$(function (){
$(“#createTopNav").click(function () { CreateTopNavigationLink() });
});
function CreateTopNavigationLink() {
var siteUrl = _spPageContextInfo.webAbsoluteUrl + “/_api/web/navigation/TopNavigationbar";
var headers = {
“accept": “application/json;odata=verbose",
“content-Type": “application/json;odata=verbose",
“X-RequestDigest": jQuery(“#__REQUESTDIGEST").val()
}
var call = jQuery.ajax({
url: siteUrl,
type: “POST",
data: JSON.stringify({
“__metadata": { type: “SP.NavigationNode" },
‘IsExternal’: true,
‘Title’: “AnotherPage",
‘Url’: “http://www.anotherpage.com"
}),
headers: headers
});
call.done(successHandler);
call.fail(failureHandler);
});

function successHandler(data, textStatus, jqXHR) {
alert(“Navigation created Successully");
}
function failureHandler(errorMessage) {
alert(“Request Failed: unable to Navigation: " + JSON.stringify(errorMessage));
}
</script>

Step-3:
After inserting the HTML and Script in the Script Editor, you will see a button on the page, viz. “Add Top Navigation Link”. Click the link to add the link “AnotherPage” Top Navigation Bar, as shown in the screenshot below.

SharePoint online Add Top Navigation Link to a Site Using REST API
SharePoint online Add Top Navigation Link to a Site Using REST API

This is how we can add a link to the top navigation in SharePoint Online using Rest API.

Add left navigation links to SharePoint Online site using Rest API

Let us see how to add left navigation links to the SharePoint Online site using Rest API. This code has been done by EnjoySharePoint author Sagar Pardeshi.

Here, we will explore represented as headings in the Quick Launch or left navigation area of the user interface in SharePoint 2013 site using REST API.

Here we tried to add custom navigation node corresponding to links in the Quick Launch area of the site using REST API using jQuery.

Add left navigation links using REST API in SharePoint

Creating Navigation in the Quick Launch( i..e Left Navigation)
REST API QuickLaunch EndPoint to use in Add_ins:

 /_api/web/Navigation/QuickLaunch

I have created the host site and have default added multiple Quick Launch navigation nodes. Now, let’s say we want to “Add one Custom navigation nodes ‘’ Notebook” in the Quick Launch(i..e Left Navigation).

add quick launch in sharepoint 2013 rest api
add quick launch in sharepoint 2013 rest api

I have Added one Custom navigation nodes “Notebook” in the Quick Launch(i..e Left Navigation) on button click.

Follow below steps:

Step-1:
Navigate to your SharePoint 2013 site and and from this page, select Site Actions | Edit Page. Then 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-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" src="../…/SiteAssets/Script/jquery-1.10.2.js"></script>

<script type="text/javascript">
$(document).ready(function ($) {
$("#createQuickLaunch").click(function () { createQuickLaunch() });
});

//Create a Quicklaunch Navigation

function createQuickLaunch() {
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/navigation/QuickLaunch";
var headers = {
"accept": "application/json;odata=verbose",
"content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}

var call = jQuery.ajax({
url: endPointUrl,
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.NavigationNode" },
'IsExternal': true,
'Title': "Notebook",
'Url': "http://www.testnotebook.com"
}),
headers: headers
});
call.done(successHandler);
call.fail(failureHandler);
}

function successHandler(data, textStatus, jqXHR) {
SP.UI.Notify.addNotification("Navigation created Successully", false);
}

function failureHandler(errorMessage) {
alert("Request Failed: unable to Navigation: " + JSON.stringify(errorMessage));
}
</script>

Final output:

On click ” Create Navigation” button.

add quick launch in sharepoint online rest api
add quick launch in sharepoint online rest api

This is, how to create left navigation or quick launch links using Rest API in SharePoint Online or SharePoint 2013/2016/2019.

Send email using rest api using SharePoint

Here in this example, I have created a sample contact us HTML form. Here there will be three fields and a button. With on click of the button, it will send the email.

Here I have added the below script to a web part page in a script editor web part in SharePoint Online or SharePoint 2013/2016.

<h1>Contact Us</h1><br/>
Name: <br/>
<input type="text" name="myname" id="myname" placeholder="Enter your Name"/><br/>
Email: <br/>
<input type="text" name="myemail" id="myemail" placeholder="Enter your Email Address"/><br/>
Message: <br/>
<textarea rows="4" cols="50" id="mymessage"></textarea><br/><br/>
<button type="button" id="fbutton">Send Message</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#fbutton").click(function(){
var sitetemplateurl = _spPageContextInfo.webServerRelativeUrl + "_api/SP.Utilities.Utility.SendEmail";
var name = $("#myname").val();
var from = $("#myemail").val();
var msg = 'From: ' + name + '<br/><br/>' + 'Email: ' + from + '<br/><br/><br/>' + $("#mymessage").val();

$.ajax({
contentType: 'application/json',
url: sitetemplateurl,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': from,
'To': { 'results': ['[email protected]'] },
'Body': msg,
'Subject':'New Email From SharePoint Online using RestAPI'
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('Message sent successfully !!!');
$("#myname").val(");
$("#myemail").val(");
$("#mymessage").val(");
},
error: function (err) {
alert(JSON.stringify(err));
}
});
});
});
</script>

Once save the page, the page will appear like below:

send email using rest api sharepoint 2013
sharepoint rest api send email

After saving the page, after clicking on the button the email will go like below:

send email using rest api sharepoint online
sharepoint rest api send email

SharePoint rest api send email

The below code block helps to send email to a user with the help of jQuery and REST service in SharePoint 2013/2016/2019.

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

<script>
function processSendEmails() {
    var from = ‘[email protected]’,
        to = ‘[email protected]’,
        body = ‘Hello World Body’,
        subject = ‘Hello World Subject’;
    alert(“Sending email to Krishna”);
    // Call sendEmail function
    sendEmail(from, to, body, subject);
    alert(“Email sent Successfully”);
}

function sendEmail(from, to, body, subject) {
    try {
        //Get the relative url of the site
        var siteurl = _spPageContextInfo.webAbsoluteUrl;
        alert(“Site URL=”+siteurl);
        var urlTemplate = siteurl + “/_api/SP.Utilities.Utility.SendEmail”;
        alert(“URLTemplate=”+urlTemplate);
        $.ajax({
            contentType: ‘application/json’,
            url: urlTemplate,
            type: “POST”,
            data: JSON.stringify({
                ‘properties’: {
                    ‘__metadata’: {
                        ‘type’: ‘SP.Utilities.EmailProperties’
                    },
                    ‘From’: ‘[email protected]’,
                    ‘To’: { ‘results’: [‘[email protected]’] },
                    ‘Body’: body,
                    ‘Subject’: subject
                }
            }),
            headers: {
                “Accept”: “application/json;odata=verbose”,
                “content-type”: “application/json;odata=verbose”,
                “X-RequestDigest”: jQuery(“#__REQUESTDIGEST”).val()
            },
            success: function(data) {
                alert(‘Email Sent Successfully’);
            },
            error: function(err) {
                alert(‘Error in sending Email: ‘ + JSON.stringify(err));
            debugger;
            }
        });
    }
    catch (error) {
    }
}
$(document).ready(function () {
    SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, processSendEmails);
});
</script>

How does this code works?

  • Save this script as sendemail.js
  • Upload the script in sharepoint document / asserts library
  • Create a web part page add the content editor web part
  • Add the javascript in a content editor web part or script editor web part

If we read the code closely this script gets triggered on page load.

The output will be as follows.

Send Email with jQuery and REST API in SharePoint
Send Email with jQuery and REST API in SharePoint

Value does not fall within the expected range in SharePoint Rest API

This Rest API SharePoint tutorial explains, how to resolve the error “Value does not fall within the expected range” which comes while working with Rest API in SharePoint 2013/2016/Online

Recently when I was trying to create a folder inside the Shared Documents folder using Rest API I got the below error: System.ArgumentException. Value does not fall within the expected range.

Value does not fall within the expected range in SharePoint Rest API
Value does not fall within the expected range in SharePoint Rest API

Value does not fall within the expected range in SharePoint Rest API

Below is the code which I was writing to create folder inside document library 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/folders";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Shared Documents/Folder1'}),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});

The problem was with the below line. The backslash (/) we have given before /Shared Documents was causing the issue.

data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Shared Documents/Folder1'}),

To resolve the issue follow the below solution.

The path should take without backslash (/) and it worked.

data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': 'Shared Documents/Folder1'}),

This is how to fix the error Value does not fall within the expected range in Rest api.

SharePoint custom alerts using javascript and rest API

Let us see, how to display custom alerts in SharePoint page using JavaScript REST API and bootstrap.

Here I have created a SharePoint list to keep the alert and set the duration of the alert which will be shown on the page.

Steps for creating a custom alert in SharePoint

Step 1: Login to the SharePoint site and create a custom list as below screenshot.

display custom alert message in SharePoint using REST API
sharepoint custom alerts
custom alert javascript
custom alert javascript

Step 2: In the Level column, I have added some options for alert color so you can change the alert settings based on your requirement.

Suppose your alert comes under a WARNING then you can choose Red(Important), If your alert comes under Notification then you can choose Yellow(Notification) like this.

javascript custom alert
javascript custom alert in SharePoint Online

Step 3: Next create a page and add a script editor web part in your page and add the below code.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<script src="https://pikasha12.sharepoint.com/sites/DLH/_layouts/15/SP.Runtime.js" type="text/javascript">

<script src="https://pikasha12.sharepoint.com/sites/DLH/_layouts/15/SP.js" type="text/javascript">

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
var CustomAlertLabel = CustomAlertLabel || {};
  
 CustomAlertLabel.MyMessage = (function () {
     return {
         init: init
     };
     function init() {
           SP.SOD.executeFunc('sp.js', 'SP.ClientContext', generateLinks);
                  
         function generateLinks() {   
             //List name where we saved the message and other properties
             var announcementList = 'CustomAlert';
             var siteAbsoluteUrl = _spPageContextInfo.siteAbsoluteUrl;    
             //Get current date with 00:00:00 as time 
             //so that the message will be displayed even if the End Date is Today                
             var today = new Date();   
             var d = today.toISOString().substring(0,10) + "T00:00:00";
                         
             var endpoint = siteAbsoluteUrl + "/_api/web/lists/GetByTitle('" + announcementList + "')/items?$filter=Start_x0020_Date le datetime'" + d + "' and End_x0020_Date ge datetime'" + d + "'";
             //AJAX call to get List Items and filter applied in URL
             $.ajax({
                 url: endpoint,
                 type: "GET",
                 dataType: "json",
                 beforeSend: function (xhr) {
                     xhr.setRequestHeader("accept", "application/json; odata=verbose");
                 }
                 }).then(function (data) {
                     var results = data.d.results;               
                     for (var i = 0; i < results.length; ++i) {   
                       var messageContent = results[i].Body; 
                       var status = results[i].Level;
                        
                       var newDiv = "";
                       //applying css based on the Level of message
                       if(status.match("^Red")) {
                         newDiv = "<div id=messageDiv"+ i +" class='alert-scroll alert-danger'><marquee direction='right'>";
                       }
                       else if(status.match("^Yellow")) {
                         newDiv = "<div id=messageDiv"+ i +" class='alert-scroll alert-warning'><marquee direction='right'>";       
                       }
                       else if(status.match("^Green")){
                         newDiv = "<div id=messageDiv"+ i +" class='alert-scroll alert-success'><marquee direction='right'>";       
                       }
                       else {
                         newDiv = "<div id=messageDiv"+ i +" class='alert-scroll alert-info'><marquee direction='right'>";           
                       }
                          
                         $("#mymessage").append(newDiv + messageContent + '</marquee></div>');  
                         $('.breadcrumb').hide();
                       var disappearTime = results[i].SecondsToDisappear;
                       //Disappear the message based on number of seconds
                       if(disappearTime != null && disappearTime != 0) {
                         disappearTime = disappearTime*1000;
                         $('#messageDiv'+i).delay(disappearTime).fadeOut('slow');                          
                       }
                     }                   
                 });
             }    
         }
 }) ();

     $.ready(CustomAlertLabel.MyMessage.init());
     </script>
 
<style>
    .alert-scroll p {
    display: block!important;
    width: 25%!important;
    margin: 0px!important;
    color: white!important;
}
    .alert-scroll {
    border-radius: 7px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    }

</style>

<div id="mymessage">

</div>

Step 4: Once you click on Save button, You can able to see the alert in top of your page with different color which you have set in your list.

display custom alert message using rest api in SharePoint Online
display custom alert message using rest api in SharePoint Online

Step 5: Suppose I have set Green color as per the below screenshot then

display custom alert message using rest api in SharePoint 2013
display custom alert message using rest api in SharePoint 2013

The alert message should show like below image

display custom alert message using rest api in SharePoint 2016
display custom alert message using rest api in SharePoint 2016

Step 6: Suppose I have set Yellow color as per the below screenshot then

display custom alert message using rest api in SharePoint 2019
display custom alert message using rest api in SharePoint 2019

The alert message should show like below image.

display custom alert message using rest api in SharePoint online
display custom alert message using rest api in SharePoint online

Note: Make sure you have set the time limit of the alert so once it crossed the time , it will automatically disappear from page.

Here I have used this code in a separate page but this alert should be present inside your master page.

Congratulations!! 🎉👏

We have reached the end of our journey. I hope you enjoyed learning with me and now feel confident to continue on to your next adventure.

Create a Custom People Directory using REST API in SharePoint

Let us see, how to use REST API to get data from the custom people directory.

Let’s begin to create a custom people directory by using SharePoint out of box contact list that contains custom columns as below screenshot.

Create a Custom People Directory using REST API in SharePoint Online
Create a Custom People Directory using REST API in SharePoint online

Let’s see how we can retrieve data using Rest API and show the result in a script editor web part in SharePoint.

Create a javaScript file in Notepad ++ and paste the below code inside a script editor web part in SharePoint page or you can add it inside Visual Studio to make it Visual web part.

<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>

<script>
function LoadContacts(firstName)
{
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Contacts')/items?$select=Title,FirstName&$filter=(FirstName eq '"+firstName+"')",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR)
{
$('#JSONData').empty();
$.each(data.d.results, function( index, value )
{
$('#JSONData').append("<h1>" + value.Title + value.FirstName +"</h1>" + "<h2>" + value.FirstName + "</h2>");
});
});
call.fail(function (jqXHR,textStatus,errorThrown)
{
alert("Error retrieving Tasks: " + jqXHR.responseText);
});
}
</script>


Search By First Name: <input type="text" id="FirstName">
<input value="Get Contacts" type="button" onClick=LoadContacts($('#FirstName').val());>​
<div id="JSONData"><div>

One thing to notice here, we are using jQuery and Ajax to call the REST API. Using a Search box to search names that match with the Contact’s name.

The above code will parse the JSON data and append the parsed data in the JSON Data div.

Now we go ahead to debug this code. So we need to enter any name in the Text box to see the result.

Create a Custom People Directory using REST API in SharePoint
Create a Custom People Directory using REST API in SharePoint

Since we got the data already, that we can apply custom HTML and CSS to show the results in a nicely formatted way.

Congratulations!! 🎉👏

We have reached the end of our journey. I hope you enjoyed learning with me and now feel confident to continue on to your next adventure.

Create a custom User profile web part using SharePoint REST API and bootstrap

Let us see, how to create a custom user profile web part using the SharePoint REST API and bootstrap. Here I have created a simple web part that can retrieve the current user properties and show them on a SharePoint page using REST API.

Below is the example of the custom user profile Web part in SharePoint with Rest API and bootstrap.

Step 1: Login to your SharePoint site -> Create a web part page. Then open the web part page and Add a Script editor Web part into the page.

Step 2: The below is the tested code which you can copy and paste it inside the script editor Web part.

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<style type="text/css">
    body{
    background: -webkit-linear-gradient(left, #3931af, #00c6ff);
}
.emp-profile{
    padding: 3%;
    margin-top: 3%;
    margin-bottom: 3%;
    border-radius: 0.5rem;
    background: #fff;
}
.profile-img{
    text-align: center;
}
.profile-img img{
    width: 70%;
    height: 100%;
}
.profile-img .file {
    position: relative;
    overflow: hidden;
    margin-top: -20%;
    width: 70%;
    border: none;
    border-radius: 0;
    font-size: 15px;
    background: #212529b8;
}
.profile-img .file input {
    position: absolute;
    opacity: 0;
    right: 0;
    top: 0;
}
.profile-head h5{
    color: #333;
}
.profile-head h6{
    color: #0062cc;
}
.profile-edit-btn{
    border: none;
    border-radius: 1.5rem;
    width: 70%;
    padding: 2%;
    font-weight: 600;
    color: #6c757d;
    cursor: pointer;
}
.proile-rating{
    font-size: 12px;
    color: #818182;
    margin-top: 5%;
}
.proile-rating span{
    color: #495057;
    font-size: 15px;
    font-weight: 600;
}
.profile-head .nav-tabs{
    margin-bottom:5%;
}
.profile-head .nav-tabs .nav-link{
    font-weight:600;
    border: none;
}
.profile-head .nav-tabs .nav-link.active{
    border: none;
    border-bottom:2px solid #0062cc;
}
.profile-work{
    padding: 14%;
    margin-top: -15%;
}
.profile-work p{
    font-size: 12px;
    color: #818182;
    font-weight: 600;
    margin-top: 10%;
}
.profile-work a{
    text-decoration: none;
    color: #495057;
    font-weight: 600;
    font-size: 14px;
}
.profile-work ul{
    list-style: none;
}
.profile-tab label{
    font-weight: 600;
}
.profile-tab p{
    font-weight: 600;
    color: #0062cc;
}
</style>
<script type='text/javascript'>  
    var workEmail = "";  
    var EmployeeID = "";  
    var Division = "";  
    var userDisplayName = "";  
    var AccountName = "";  
    var firstName="";
    var lastname="";
    var skillset="";
    var webURL="";
    var pictureLink="";
    var department="";
    var phone="";
    $.ajax({  

        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",  
        headers: { Accept: "application/json;odata=verbose" },  
        success: function (data) {  
            try {  
                //Get properties from user profile Json response  
                userDisplayName = data.d.DisplayName;  
                AccountName = data.d.AccountName;  
                var properties = data.d.UserProfileProperties.results;  
                for (var i = 0; i < properties.length; i++) {  
                  var property = properties[i]; 
                    if (property.Key == "WorkEmail") {  
                        workEmail = property.Value;  
                    }  

                    if (property.Key == "EmployeeID") {  
                        EmployeeID = property.Value;  
                    }  
                    if (property.Key == "Division") {  
                        Division = property.Value;  
                    }  
                  if (property.Key == "SPS-Skills") {  
                        skillset= property.Value;  
                    }  
                 if (property.Key == "WebSite") {  
                        webURL= property.Value;  
                    }  
                     if (property.Key == "FirstName") {  
                        firstName= property.Value;  
                    }  
                  if (property.Key == "FirstName") {  
                        lastname= property.Value;  
                    }  
                     if (property.Key == "Department") {  
                        department= property.Value;  
                    }  
                    if (property.Key == "WorkPhone") {  
                        phone= property.Value;  
                    }  
					if (property.Key == "PictureURL") {  
                        pictureLink= property.Value;  
                    }  			

                }  
				
				var picture='';
				var namedetails='';
				var skill='';
				var contatcDetails='';
				picture +="<img src= '"+ pictureLink +"' alt=''/>";  
				namedetails +="<div class='profile-head'>";
                namedetails +="<h5>"+userDisplayName +" </h5>";
                namedetails +="<h6>"+department +" </h6>";	
                namedetails +=' <p class="proile-rating">RANKINGS : <span>8/10</span></p> <ul class="nav nav-tabs" id="myTab" role="tablist"><li class="nav-item"><a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">About</a></li><li class="nav-item"><a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Timeline</a></li></ul>';				
                namedetails +="</div>"; 
				
				skill +="<div class='profile-work'>";
				skill +='<p>WORK LINK</p><a href="">' +webURL+'</a><br/>';
				skill +='<p>SKILLS</p><a href="">' +skillset+'</a><br/>';
				skill +='</div>';
				
				contatcDetails +='<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">';
				contatcDetails +='<div class="row"><div class="col-md-6"><label>User Id</label></div><div class="col-md-6"><p>'+AccountName+'</p></div></div>';
				contatcDetails +='<div class="row"><div class="col-md-6"><label>Name</label></div><div class="col-md-6"><p>'+userDisplayName+'</p></div></div>';
				contatcDetails +=' <div class="row"><div class="col-md-6"><label>Email</label></div><div class="col-md-6"><p>'+workEmail+'</p></div></div>';
				contatcDetails +='<div class="row"><div class="col-md-6"><label>Phone</label></div><div class="col-md-6"><p>'+phone+'</p></div></div>';
				contatcDetails +='<div class="row"><div class="col-md-6"><label>Profession</label></div><div class="col-md-6"><p>'+department+'</p></div></div>';
				
				contatcDetails +='</div>';
				
				 $("#profImage").append(picture);
				 $("#UserNamedetails").append(namedetails);
				 $("#profileDetails").append(skill);
				 $("#myTabContent").append(contatcDetails);
				 
            } catch (err2) {  
                //alert(JSON.stringify(err2));  
            }  
        },  
        error: function (jQxhr, errorCode, errorThrown) {  
            alert(errorThrown);  
        }  
    });  

</script>  

<div class="container emp-profile">
            <form method="post">
                <div class="row">
                    <div class="col-md-4">
                        <div class="profile-img" id="profImage">
                            
                            <div class="file btn btn-lg btn-primary">
                                Change Photo
                                <input type="file" name="file"/>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6" id="UserNamedetails">
                    </div>
                    <div class="col-md-2">
                        <input type="submit" class="profile-edit-btn" name="btnAddMore" value="Edit Profile"/>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4" class="profileDetails" id="profileDetails"> 
					
                    </div>
                    <div class="col-md-8">
                        <div class="tab-content profile-tab" id="myTabContent">
                           
                           </div>  							
                     </div>
                        </div>
                    </div>
            </form>           
        </div></DIV>

Step 3: The below is the output of my code.

custom user profile web part using rest api and bootstrap
custom user profile web part using rest api and bootstrap

Note: The below are the other properties you can retrieve using REST API.

List of User Properties (Use the GetPropertiesFor function for these):

  • AccountName
  • DirectReports
  • DisplayName
  • Email
  • ExtendedManagers
  • ExtendedReports
  • IsFollowed
  • LatestPost
  • Peers
  • PersonalUrl
  • PictureUrl”
  • Title
  • UserProfileProperties
  • UserUrl

List of User Profile Properties (Use the GetUserProfilePropertyFor function for these)

  • AboutMe
  • SPS-LastKeywordAdded
  • AccountName
  • SPS-Locale
  • ADGuid
  • SPS-Location
  • Assistant
  • SPS-MasterAccountName
  • CellPhone
  • SPS-MemberOf
  • Department
  • SPS-MUILanguages
  • EduExternalSyncState
  • SPS-MySiteUpgrade
  • EduOAuthTokenProviders
  • SPS-O15FirstRunExperience
  • EduPersonalSiteState
  • SPS-ObjectExists
  • EduUserRole
  • SPS-OWAUrl
  • Fax
  • SPS-PastProjects
  • FirstName
  • SPS-Peers
  • HomePhone
  • SPS-PersonalSiteCapabilities
  • LastName
  • SPS-PersonalSiteInstantiationState
  • Manager
  • SPS-PhoneticDisplayName
  • Office
  • SPS-PhoneticFirstName
  • PersonalSpace
  • SPS-PhoneticLastName
  • PictureURL
  • SPS-PrivacyActivity
  • PreferredName
  • SPS-PrivacyPeople
  • PublicSiteRedirect
  • SPS-ProxyAddresses
  • QuickLinks
  • SPS-RegionalSettings-FollowWeb
  • SID
  • SPS-RegionalSettings-Initialized
  • SISUserId
  • SPS-ResourceAccountName
  • SPS-AdjustHijriDays
  • SPS-ResourceSID
  • SPS-AltCalendarType
  • SPS-Responsibility
  • SPS-Birthday
  • SPS-SavedAccountName
  • SPS-CalendarType
  • SPS-SavedSID
  • SPS-ClaimID
  • SPS-School
  • SPS-ClaimProviderID
  • SPS-ShowWeeks
  • SPS-ClaimProviderType
  • SPS-SipAddress
  • SPS-ContentLanguages
  • SPS-Skills
  • SPS-DataSource
  • SPS-SourceObjectDN
  • SPS-Department
  • SPS-StatusNotes
  • SPS-DisplayOrder
  • SPS-Time24
  • SPS-DistinguishedName
  • SPS-TimeZone
  • SPS-DontSuggestList
  • SPS-UserPrincipalName
  • SPS-Dotted-line
  • SPS-WorkDayEndHour
  • SPS-EmailOptin
  • SPS-WorkDayStartHour
  • SPS-FeedIdentifier
  • SPS-WorkDays
  • SPS-FirstDayOfWeek
  • Title
  • SPS-FirstWeekOfYear
  • UserName
  • SPS-HashTags
  • UserProfile_GUID
  • SPS-HireDate
  • WebSite
  • SPS-Interests
  • WorkEmail
  • SPS-JobTitle
  • WorkPhone
  • SPS-LastColleagueAdded

user profile properties REST API for current user

1. Get all properties of current user

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

2. Get single property of current user

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties/PictureUrl
OR
http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl

3. Get multiple properties for the current user

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl,AccountName

Currency Converter in SharePoint Online using JavaScript and REST API

Let us see, how to implement Currency Converter in SharePoint Online using JavaScript and REST API.

Step 1: Please look into the below screenshot. Here I used a simple script Editor Web part to build the code.

Below is the screenshot of my page.

SharePoint Online currency converter using rest api

Step 2: You can simply copy and paste the below code and used it inside a Script Editor Web part. In this code, I used Bootstrap and JavaScript as a reference.

<html>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">                                      
<div class="jumbotron">
  <div class="container">
     <h2>Currency Converter in SharePoint Online </h2> 
   <form class="form-inline">
     <div class="form-group mb-2">
        <input type="number" class="form-control" id="amount"/>
     </div>
     <div class="form-group mx-sm-3 mb-2">
        <select class="form-control" id="from_currency" required>
         <option value="AED">AED</option>
		<option value="ARS">ARS</option>
		<option value="AUD">AUD</option>
		<option value="BGN">BGN</option>
		<option value="BRL">BRL</option>
		<option value="BSD">BSD</option>
		<option value="CAD">CAD</option>
		<option value="CHF">CHF</option>
		<option value="CLP">CLP</option>
		<option value="CNY">CNY</option>
		<option value="COP">COP</option>
		<option value="CZK">CZK</option>
		<option value="DKK">DKK</option>
		<option value="DOP">DOP</option>
		<option value="EGP">EGP</option>
		<option value="EUR">EUR</option>
		<option value="FJD">FJD</option>
		<option value="GBP">GBP</option>
		<option value="GTQ">GTQ</option>
		<option value="HKD">HKD</option>
		<option value="HRK">HRK</option>
		<option value="HUF">HUF</option>
		<option value="IDR">IDR</option>
		<option value="ILS">ILS</option>
		<option value="INR">INR</option>
		<option value="ISK">ISK</option>
		<option value="JPY">JPY</option>
		<option value="KRW">KRW</option>
		<option value="KZT">KZT</option>
		<option value="MXN">MXN</option>
		<option value="MYR">MYR</option>
		<option value="NOK">NOK</option>
		<option value="NZD">NZD</option>
		<option value="PAB">PAB</option>
		<option value="PEN">PEN</option>
		<option value="PHP">PHP</option>
		<option value="PKR">PKR</option>
		<option value="PLN">PLN</option>
		<option value="PYG">PYG</option>
		<option value="RON">RON</option>
		<option value="RUB">RUB</option>
		<option value="SAR">SAR</option>
		<option value="SEK">SEK</option>
		<option value="SGD">SGD</option>
		<option value="THB">THB</option>
		<option value="TRY">TRY</option>
		<option value="TWD">TWD</option>
		<option value="UAH">UAH</option>
		<option value="USD" selected>USD</option>
		<option value="UYU">UYU</option>
		<option value="VND">VND</option>
		<option value="ZAR">ZAR</option>
        </select>
      </div>
      <div class="form-group mx-sm-3 mb-2">
        <label>convert to</label><div class="rate" id="rate"></div>
        <select class="form-control" id="to_currency" required>
        <option value="AED">AED</option>
		<option value="ARS">ARS</option>
		<option value="AUD">AUD</option>
		<option value="BGN">BGN</option>
		<option value="BRL">BRL</option>
		<option value="BSD">BSD</option>
		<option value="CAD">CAD</option>
		<option value="CHF">CHF</option>
		<option value="CLP">CLP</option>
		<option value="CNY">CNY</option>
		<option value="COP">COP</option>
		<option value="CZK">CZK</option>
		<option value="DKK">DKK</option>
		<option value="DOP">DOP</option>
		<option value="EGP">EGP</option>
		<option value="EUR">EUR</option>
		<option value="FJD">FJD</option>
		<option value="GBP">GBP</option>
		<option value="GTQ">GTQ</option>
		<option value="HKD">HKD</option>
		<option value="HRK">HRK</option>
		<option value="HUF">HUF</option>
		<option value="IDR">IDR</option>
		<option value="ILS">ILS</option>
		<option value="INR" selected>INR</option>
		<option value="ISK">ISK</option>
		<option value="JPY">JPY</option>
		<option value="KRW">KRW</option>
		<option value="KZT">KZT</option>
		<option value="MXN">MXN</option>
		<option value="MYR">MYR</option>
		<option value="NOK">NOK</option>
		<option value="NZD">NZD</option>
		<option value="PAB">PAB</option>
		<option value="PEN">PEN</option>
		<option value="PHP">PHP</option>
		<option value="PKR">PKR</option>
		<option value="PLN">PLN</option>
		<option value="PYG">PYG</option>
		<option value="RON">RON</option>
		<option value="RUB">RUB</option>
		<option value="SAR">SAR</option>
		<option value="SEK">SEK</option>
		<option value="SGD">SGD</option>
		<option value="THB">THB</option>
		<option value="TRY">TRY</option>
		<option value="TWD">TWD</option>
		<option value="UAH">UAH</option>
		<option value="USD">USD</option>
		<option value="UYU">UYU</option>
		<option value="VND">VND</option>
		<option value="ZAR">ZAR</option>
        </select>
      </div>  
      <button class="btn calculate-btn btn btn-success mb-2" id="exchange">Convert</button>
    </form>
    <div class="result">
      <p>
        <span class="given-amount"></span> 
        <span class="base-currency"></span>
        <span class="final-result" id="to_ammount"></span> 
        <span class="second-currency"></span>
      </p>
    </div>
  </div> 
</div>
</body>
</html>

Step 3: Below is my script which can help us to build this app. Here I called api.exchangerate-api.com to get currency rate.

<script language="JavaScript">
var from_currencyEl = document.getElementById('from_currency');
var amountInput = document.getElementById('amount');
var to_currencyEl = document.getElementById('to_currency');
var to_ammountEl = document.getElementById('to_ammount');
var rateEl = document.getElementById('rate');
var exchange = document.getElementById('exchange');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');

exchange.addEventListener('click', convertCurrency);

  function convertCurrency(event) {
  event.preventDefault();
  var amount = amountInput.value;
  var from_currency = from_currencyEl.value;
  var to_currency = to_currencyEl.value;
  var result = 0;
  toShowAmount.innerHTML = amount;
  toShowBase.textContent = from_currency + ' = ';
  toShowSecond.textContent = to_currency;
  
  var restUrl = "https://api.exchangerate-api.com/v4/latest/"+from_currency+"";

  $.ajax(
    {
       url: restUrl,
        method: "GET",
        headers:
        {
           "accept": "application/json;odata=verbose",
        },
       success: onSuccess,
       error: onError
    });
  
  function onSuccess(data) {
    if(data)
    {
       var rate = data.rates[to_currency];
	   rateEl.innerText = "1"+ from_currency+" = "+rate+" "+to_currency+"";
	   toShowResult.textContent = (amountInput.value * rate).toFixed(2);
    }
}
 
function onError(err) {
   var response =
   {
       header: "error",
       message: err
   };
}
  
    }
</script>

Step 4: In the below screenshot, I converted the 12 USD to INR and the expected result would be 918.75 INR.

In the button click, I called addEventListener to call the currencyConverter method.

SharePoint Online currency converter using javascript

Step 5: Below is one more example where I converted 70 SGD to EGP. The expected result would be 769 EGP.

Currency Converter in SharePoint Online using JavaScript and REST API

This is an example of creating a simple currency converter in SharePoint Online using REST and JavaScript.

You may also like the following SharePoint Rest API tutorials:

In this tutorial we learned:

  • What is SharePoint Rest API
  • How SharePoint REST API works
  • SharePoint Rest API HTTP commands
  • SharePoint 2013 REST endpoints examples
  • Advantages of using rest api in SharePoint
  • How to get and send the form digest value
  • SharePoint Rest API Examples
  • Retrieve user display name using Rest API in SharePoint Online/2013
  • Delete SharePoint 2013/Online list Item using REST API
  • Delete SharePoint 2013/Online list using REST API
  • get alternate languages from language settings in SharePoint using Rest API
  • Retrieve all lists and libraries using Rest API in SharePoint
  • Retrieve Rich Textbox content as plain text using REST API SharePoint 2013
  • SharePoint Online add top navigation link using Rest API
  • Add left navigation links to SharePoint Online site using Rest API
  • Value does not fall within the expected range in SharePoint Rest API
  • Send email using rest api using SharePoint
  • Hi, If SharePoint REST services are invoked from a custom web application how would a user authentication and authorisation takes place for the REST service call? Does it require user-only policy and simply need to provide user access token? This user has already authenticated in the custom web application using 3rd-party SSO solution.

  • >