Nintex Workflow – How to handle the JSON Response from REST API

Sathish Nadarajan
 
Solution Architect
April 10, 2019
 
Rate this article
 
Views
4293

Recently, I met with an interesting scenario that, from a Nintex Workflow, I am making a REST API, which returns a JSON object and the API is capable to return only JSON. I need to process result from my Workflow. When I was searching for a JSON Parser action in the Nintex, Unfortunately, there is no action like that in Nintex. And this has been raised in the Nintex User Voice as well. Hence, they may include this action in the upcoming releases I guess.

But, we must find a work around for that and the workaround is also very simple. We have a Data Type called Collection and Dictionary on the Nintex. By that, we can easily process the JSON. But, we have to use the foreach at least once, to actual processing.

The Set Workflow Variable Action configuration is like below.

Always the APIResonse will be Text and we need to create a Collection Variable and assign the Text to the Collection. Then the collection can be manipulated.

The Sample JSON Object, which I am getting from the API is as follows.

 {
   "Entry": [
     {
       "Employee_ID": "10001",
       "LeaveDetails": [
         {
           "LeaveType": "Casual",
           "Date": "2016-11-05",
           "ApprovedDate": "2018-10-31T22:15:44.112-07:00",
           "Unit": "Days",
           "Units": "1"
         },
         {
           "LeaveType": "Casual",
           "Date": "2016-11-05",
           "ApprovedDate": "2018-10-31T22:15:44.112-07:00",
           "Unit": "Days",
           "Units": "1"
         },
  {
           "LeaveType": "Casual",
           "Date": "2016-11-05",
           "ApprovedDate": "2018-10-31T22:15:44.112-07:00",
           "Unit": "Days",
           "Units": "1"
          
       ],
       "Employee Name": "Sathish Nadarajan"
     }
   ]
 }
 

I have a parent entry called “Entry” which has the childs, EmpID, EmployeeName, LeaveDetails. The Leave Details is again an Array. Hence, that can be treated as a Dictionary. The EmpID, we need to get the “Entry” Collection.

Save that on the Output Variable “ReportEntry” as Collection.

From the “ReportEntry”, Now, let us get the “LeaveDetails” collection.

Now, we can do the ForEach loop and manipulate the details.

The Output Value TimeOffDetail is nothing but a Dictionary Variable. From that dictionary, we can access the appropriate variable like Date, Units etc.,

We can manipulate any tags by giving the appropriate index and tag names as below.

By this way, we can manipulate the JSON objects in the Nintex Workflows.

 

Happy Coding,

Sathish Nadarajan.

Category : Nintex, RestAPI

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Making Rest API Calls made much simpler using RestSharp in C#

Sathish Nadarajan
 
Solution Architect
November 19, 2018
 
Rate this article
 
Views
5046

Usually from a C# code, calling an API is somewhat cumbersome process to pass the body message and the authentication host headers. Recently, I was trying to look for an alternative and found an interesting NuGet Package called RestSharp, which handles all our headaches and made the API execution much simpler. (This is an Open Source which is not provided by Microsoft. Hence, I am leaving this with the readers to consume that).

1. From our C# application, add the RestSharp NuGet Package as below.

clip_image002

2. Once, added, add the namespace.

3. The complete sample code as below.

No more hassles of creating the HTTP objects.

 namespace CallRestAPI.Console
 
 {
 
 using RestSharp;
 
 class Program
 
 {
 
 static void Main(string[] args)
 
 {
 
 // Create a RestClient
 
 var client = new RestClient("https://URL of the API");
 
 // Define the HTTP Method
 
 var request = new RestRequest(Method.GET);
 
 //Add the headers
 
 request.AddHeader("api-key", "ANY  Authentication Keys if required");
 
 request.AddHeader("Content-Type", "application/json");
 
 //Add the Body Parameter
 
 request.AddParameter("undefined", "BODY", ParameterType.RequestBody);
 
 //Execute the Call
 
 IRestResponse response = client.Execute(request);
 
 }
 
 }
 
 }
 

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Upload File to SharePoint Office 365 Programmatically using C# CSOM – /_api/web/GetFolderByServerRelativeUrl – PostAsync – HttpClient

Sathish Nadarajan
 
Solution Architect
September 20, 2018
 
Rate this article
 
Views
9752

Recently I was doing a POC to upload a bunch of documents programmatically to SharePoint Document Library using C# CSOM. Initially I was trying with the RestAPI provided by Microsoft and wanted to Share the entire steps to the readers. There are some other optimal faster ways are there. But again, this is the first approach tried. This is not the optimal solution. The issues, which we have in this approach and the easiest work around for that will be addressed on the upcoming article.

As usual, I was creating a Console application which will read the files from the file system and upload into the SharePoint using the RestAPI.

 namespace Office365.Console
 {
     using Microsoft.SharePoint.Client;
     using Newtonsoft.Json;
     using System;
     using System.Collections.Concurrent;
     using System.IO;
     using System.Net;
     using System.Net.Http;
 
     class Program
     {
         private static ConcurrentDictionary<Uri, RESTFormDigest> FormDigests { get; set; }
 
         static void Main(string[] args)
         {
             UploadSmallerFiles();
             System.Console.WriteLine("Completed");
             System.Console.ReadLine();
         }
 
         static string siteUrl = "https://*****.sharepoint.com/sites/DeveloperSite/";
         static string userName = "sathish@******.com";
         static string password = "*********";
 
         public async static void UploadSmallerFiles()
         {
             try
             {
                 OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
                 using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 {
                     Web web = ctx.Web;
                     ctx.Load(web);
                     ctx.Load(web.Lists);
                     ctx.ExecuteQueryRetry();
                     List list = web.Lists.GetByTitle("D1");
                     ctx.Load(list);
                     ctx.ExecuteQueryRetry();
                     Folder folder = list.RootFolder.EnsureFolder("Folder1");
                     ctx.Load(folder);
                     ctx.ExecuteQueryRetry();
 
 
                     var credentials = new SharePointOnlineCredentials(userName, OfficeDevPnP.Core.Utilities.EncryptionUtility.ToSecureString(password));
 
                     var targetUri = new Uri(siteUrl);
                     var rawCookie = (credentials.GetAuthenticationCookie(targetUri) ?? string.Empty).TrimStart("SPOIDCRL=".ToCharArray());
 
                     var CookieContainer = new CookieContainer();
                     CookieContainer.Add(new Cookie("FedAuth", rawCookie, string.Empty, targetUri.Authority));
                     CookieContainer.Add(new Cookie("SPOIDCRL", rawCookie, string.Empty, targetUri.Authority));
 
                     var clientHandler = new HttpClientHandler()
                     {
                         CookieContainer = CookieContainer,
                         UseCookies = true,
                     };
 
                     var client = new HttpClient(clientHandler);
                     client.BaseAddress = new Uri(siteUrl);
                     client.Timeout = TimeSpan.FromMinutes(60);
                     client.DefaultRequestHeaders.Add("Accept", @"application/json;odata=verbose");
                     client.DefaultRequestHeaders.Add("X-RequestDigest", GetFormRequestDigest(siteUrl));
 
                     string serverRelativeUrl = string.Empty;
 
                     var urlAddFile = string.Format("{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/Add(url='{2}',overwrite=true)", ctx.Web.Url, folder.ServerRelativeUrl, "SmallFile.txt");
 
 
                     var stream = System.IO.File.Open("D:\SmallFile.txt", System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                     var streamContent = new StreamContent(stream);
                     var response = await client.PostAsync(urlAddFile, streamContent);
 
 
                 }
             }
             catch (Exception ex) {
                 System.Console.WriteLine("Exception occurred : " + ex.Message);
                 System.Console.ReadLine();
             }
         }
 
 
         private static string GetFormRequestDigest(string webUrl, Guid correlationId = new Guid())
         {
             HttpResponseMessage response = null;
 
             try
             {
                 var uri = new Uri(webUrl);
 
                 var credentials = new SharePointOnlineCredentials(userName, OfficeDevPnP.Core.Utilities.EncryptionUtility.ToSecureString(password));
 
                 var targetUri = new Uri(siteUrl);
                 var rawCookie = (credentials.GetAuthenticationCookie(targetUri) ?? string.Empty).TrimStart("SPOIDCRL=".ToCharArray());
 
                 var CookieContainer = new CookieContainer();
                 CookieContainer.Add(new Cookie("FedAuth", rawCookie, string.Empty, targetUri.Authority));
                 CookieContainer.Add(new Cookie("SPOIDCRL", rawCookie, string.Empty, targetUri.Authority));
 
 
                 var clientHandler = new HttpClientHandler()
                 {
                     CookieContainer = CookieContainer,
                     UseCookies = true,
                 };
 
                 var client = new HttpClient(clientHandler);
                 client.BaseAddress = new Uri(siteUrl);
                 client.Timeout = TimeSpan.FromMinutes(60);
                 client.DefaultRequestHeaders.Add("Accept", @"application/json;odata=verbose");
 
                 var url = string.Format("{0}/_api/contextinfo", webUrl);
 
                 using (var content = new StringContent(string.Empty))
                 {
                     response = client.PostAsync(url, content).Result;
                 }
 
                 response.EnsureSuccessStatusCode();
 
                 var data = response.Content.ReadAsStringAsync().Result;
                 var info = JsonConvert.DeserializeObject<dynamic>(data);
                 FormDigests = new ConcurrentDictionary<Uri, RESTFormDigest>();
                 FormDigests[uri] = new RESTFormDigest(Convert.ToString(info["d"]["GetContextWebInformation"]["FormDigestValue"]));
 
                 return FormDigests[uri].FormDigest;
             }
             catch (Exception ex)
             {
                 return string.Empty;
             }
         }
     }
 }
 

The FormDigest Class looks below.

 namespace Office365.Console
 {
     using System;
 
     public class RESTFormDigest
     {
         public RESTFormDigest()
         {
             this.FormDigest = string.Empty;
             this.Expiry = DateTime.MinValue;
         }
 
         public RESTFormDigest(string formDigest)
         {
             this.FormDigest = formDigest;
 
             this.Expiry = DateTime.UtcNow.AddMinutes(20);
         }
 
         public string FormDigest { get; private set; }
 
         public DateTime Expiry { get; private set; }
     }
 }
 

The limitation on the above method is, we cannot upload file more than 200 MB file. Even, when we try to upload, it does not throw any exception. But, the document was not uploading. Hence, we need to find a work around for that.

But one best thing is, this will execute asynchronously. When we are trying to upload a bunch of documents, then, even in our program, if we have not implemented the multi-threaded approach, the PostAsync method will move on to the next document. But, this is a bit complex to implement.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

User Profile properties with REST API–SharePoint Office 365

Sriram
 
Technology Specialist
July 19, 2018
 
Rate this article
 
Views
26965

 

In this post lets have a look at how to get SharePoint user profile properties using the REST API.

Here is a quick reference for the REST API endpoints.

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

4) Get all properties of Specific User:

For Office 365/SharePoint Online:
http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’i:0%23.f|membership|vardhaman@siteurl.onmicrosoft.com’
For SharePoint 2013 On-Premise:
http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’domain\username’

5) Get Specific UserProfile Property of Specific User:

For Office 365/SharePoint Online:
http://siteurl/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName=’LastName’)?@v=’i:0%23.f|membership|vardhaman@siteurl.onmicrosoft.com’
For SharePoint 2013 On-Premise:
http://siteurl/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName=’LastName’)?@v=’domain\username’

 

 

 

 

 

 

Below is the function to get user profile details for the particular user.

 function gettingUserProfileByAccountName(accountName) {
 
 $.ajax({
 
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+accountName+"'",
 
 headers: {
 
 "Accept": "application/json; odata=verbose"
 
 },
 
 async: false,
 
 contentType: "application/json; odata=verbose",
 
 success: function (data) {
 
 var results;
 
 if (data.d) {
 
 results = data.d.UserProfileProperties.results;
 
 for (i = 0; i < results.length; i++) {
 
 if (results[i].Key == "WorkEmail") {
 
 $('input[title="Requestor Email"]').val(results[i].Value);
 
 }
 
 if (results[i].Key == "WorkPhone") {
 
 $('input[title="Requestor Phone"]').val(results[i].Value);
 
 }
 
 }
 
 }
 
 }
 
 });
 
 }
 

Author Info

Sriram
 
Technology Specialist
 
Rate this article
 
Sriram T has been working in IT industry for over 6 years He holds Bachelor's degree in Computer Science Engineering. Sriram write articles and blogs related to SharePoint 2013, SharePoint ...read more
 

Step by Step Procedure to Call SharePoint Office 365 REST API from Microsoft Flow

Sathish Nadarajan
 
Solution Architect
March 28, 2018
 
Rate this article
 
Views
18923

In the earlier articles, we saw various implementations in Microsoft Flow. Now, let us see how to Consume a SharePoint REST API call from Microsoft Flow.

As all of us understood, that there are a lot of Out of the Box SharePoint Actions (functionalities) are available in Microsoft Flow. But not all. Many times, we want to use REST API Calls to GET/POST data from and to SharePoint Office 365. In that case, we have an action called HTTP in Microsoft Flow. But it is not straight forward. We need to implement some sort of Authentication and Authorization techniques, so that the Flow can access the SharePoint Data Seamlessly.

Objective:

We are going to create a Flow, which will call the SharePoint REST API to get the Users within a SharePoint User Group.

Steps at High Level:

1. Create an APP in SharePoint Office 365 tenant.

2. Using the Client ID and the Client Secret ID, Get the Authentication (Access Token) from Azure Active Directory.

3. Using that Access Token, make a HTTP GET call to Get the Users on the specified Group

4. Send mail to the Admin or the requestor.

Section 1 – Create an APP in SharePoint Office 365 tenant

1. Login to the Office 365 Site Collection.

clip_image002

2. Register an APP by going to _layouts/15/appregnew.aspx.

clip_image004

3. Generate a Client ID and the Client Secret ID. Give a name for your App. Here, I have given it as “Flow2”. The App Domain and “localhost” and the Request URI as https://localhost. Though we don’t have a IIS Server setup, we can just use localhost, since we are not going to launch this app anywhere. We are going to Use this app to get the Access Token alone.

4. Go to the _layouts/15/appinv.aspx page and by using the Client ID on the above step, lookup the APP.

clip_image006

On the Permission Request XML field, paste the below XML.

<AppPermissionRequests AllowAppOnlyPolicy=”true”>

<AppPermissionRequest Scope=”http://sharepoint/content/sitecollection” Right=”FullControl” />

</AppPermissionRequests>

5. Once, the registration is completed, then by going to _layouts/15/appprincipals.aspx page, we can verify the APP with the Client ID and the Tenant ID.

clip_image008

6. With this, we are done with the APP Registration Portion.

Section 2 – Using the Client ID and Client Secret ID, get the Access token from the Flow.

1. Login to the https://flow.microsoft.com with valid credentials.

2. Click on My Flows. Create a Flow from a blank template.

clip_image010

3. Add a trigger “Manually trigger a flow” and enter the Input as GroupName and the default Value as MyGroup. (Here, you can give any value like “Enter a Group Name to fetch the Users on the group etc., ) We will be using the value to fetch the members on this group.

clip_image012

4. Add an action HTTP and Rename it as “Get Access Token”. This name is for our understanding and clarity only. We can give any name for the action. The action will be as below.

clip_image014

The Values of the Action are,

MethodPOST
Urihttps://accounts.accesscontrol.windows.net/<<TENANTID>>/tokens/oauth/2

The TenantID should be replaced with our actual tenant ID

HeadersContent-Type : application/x-www-form-urlencoded
BodyGrant_type=client_credentials&client_id=<<ClientID>>@<<TenantID>>&client_secret=<<ClientSecretID>>&resource=00000003-0000-0ff1-ce00-000000000000/<<TenantName>>.sharepoint.com@<<TenantID>>

5. Save the Flow by giving appropriate Name. In this case, I have given it as “Flow Demo”

6. Run the Flow and make sure that, we get the access token in the Body of the Output.

Section 3 – Using the Access token and make the second HTTP Call for the actual GET API call.

1. The Output of the previous action will be some thing like,

{
“token_type”: “Bearer”,
“expires_in”: “3599”,
“not_before”: “1522214470”,
“expires_on”: “1522218370”,
“resource”: “00000003-0000-0ff1-ce00-000000000000/sppalsmvp.sharepoint.com@*****TENANTID********”,
“access_token”: “*******ACCESS TOKEN*****”
}

 

2. This JSON object needs to be parsed to get the actual value – access_token.

3. For that, we are going to add another action called JSON PARSE.

clip_image016

4. The Content is the Output Body from the previous action and the Schema, is the one, which we are going to define. We require two parameters from the previous output.

a. Token_type – The value is going to be Bearer. We can hard code this on our upcoming action. But, since, this is coming as an output parameter, we are going to use this, instead of hard coding.

b. Access_token – This is the primary output expected from the previous action.

5. The schema should be,

 

{

“type”: “object”,

“properties”: {

                         “token_type”: {

                                                        “type”: “string”

                                                 },

                           “access_token”: {

                                                      “type”: “string”

                                                }

                     }

}

 

6. Now, let us add the actual HTTP action and we can also rename this. In this demo, I have not renamed. Kept as it is as HTTP.

clip_image018

7. The parameters are as below.

MethodGET
UriThe REST API URI. In my case, as we are going to get the users, the value is something like, https://SITEJNAME/_api/23b/sitegroups/getbyName(‘MyGroup’)/users?$select=Title
HeadersAuthorization : Bearer : ACCESSTOKEN

Accept : application/json;odata=verbose

8. Save the Flow and Execute it. On the output, we can see the various Users Title.

{
“d”: {
“results”: [
      {
“__metadata”: {
“id”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(10)”,
“uri”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(10)”,
“type”: “SP.User”
        },
“Title”: “Sathish Nadarajan”
      },
      {
“__metadata”: {
“id”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(14)”,
“uri”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(14)”,
“type”: “SP.User”
        },
“Title”: “User1”
      },
      {
“__metadata”: {
“id”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(15)”,
“uri”: “https://sppalsmvp.sharepoint.com/sites/TeamSite/_api/Web/GetUserById(15)”,
“type”: “SP.User”
        },
“Title”: “User2”
      }
    ]
  }
}

9. On this JSON, we can do the parsing and get the Title of the users and send mail to the requestor or we can do the rest of the jobs.

10. The overall flow will look like below.

clip_image020

Hope this helps to understand about calling the SharePoint REST APIs from the Flow.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Swagger – To Explore The Schema Specification Of The REST API Service

Krishna KV
 
Team Leader, Aspire Systems
January 1, 2017
 
Rate this article
 
Views
9368

Swagger is a simple and powerful  option for defining the interface of a REST web service. Swashbuckle combined with the API Explorer and Swagger UI provides a rich discovery, documentation and playground for the API consumers. This article provides details on how to use Swagger with REST API

1. Create a new project in Web API Project Template in Visual Studio

2. Search Swagger in Nuget package manager and install the swashbuckler

After the package is installed, it will create a new file (SwaggerConfig.cs) under the APP_Start folder. This file is the swagger configuration.

3. Create the Web API service with necessary services.

4. Run the project

5. http://localhost:62862/swagger

It will lists all the Rest API Service available

clip_image002

We can test the service in the swagger directly.

clip_image004

 /// <summary>
 /// To get a specific customer value
 /// </summary>
 /// <param name="id">Input the Customer ID </param>
 /// <returns>It will return the customer id,name and address</returns>
 public Customer Get(int id)
 {
 	return new Customer { Id = 1001, Address = "dfs", Name = "Test" };
 }

Include the API Comments in the swagger help documentation

· Include the xml documentation in the file system of the project build folder.

clip_image006

Include the code in swaggerconfig.cs

 private static string GetXmlCommentsPath()
         {
             return string.Format(@"{0}binswagger.xml", System.AppDomain.CurrentDomain.BaseDirectory);
         }
         public static void Register()
         {
             var thisAssembly = typeof(SwaggerConfig).Assembly;
 
             GlobalConfiguration.Configuration 
                 .EnableSwagger(c =>
                     {
                         c.IncludeXmlComments(GetXmlCommentsPath());
 ....

clip_image008

Customize swagger ui using the stylesheet and Javascript

· Include the custom CSS and javascript file in the project and embedded the file to project.

· Select the css and javascript goto the properties

clip_image010

clip_image012

Swagger-cus.css

 .swagger-section #header {
     background-color: #c3d9ec;
   }
 

Swagger-cus.js

 $(document).ready(function () {
     var logo = $('#logo .logo__img');
     logo[0].src = '/content/logo.png';
     $('#logo .logo__title').text('API Explorer');
 });

clip_image014

Author Info

Krishna KV
 
Team Leader, Aspire Systems
 
Rate this article
 
Krishna K.V has been working in IT Industry for over 7+ years. He holds a Master Degree in Information Technology. He is more interested to learn and share new technologies, ...read more
 

How to call WebApi in SharePoint 2013 using Javascript

Sathish Nadarajan
 
Solution Architect
July 2, 2015
 
Rate this article
 
Views
15684

In the previous article, we saw how to create a WebAPI. Now, let us see a small piece of code, how to call that API from your SharePoint 2013 site using Javascript.

I assume that, we have created the API successfully and the API is hosted properly. Now, on our Javascript, a simple call like below will do the rest of the things.

 try{
 			 $.getJSON("http://localhost:47270/api/test/MyAction/Test?callback=?",
              function (Data) {
               alert(Data);
              })
              .fail(
              function (jqXHR, textStatus, err) {
              alert('Fail ' + err);
              });
 			 }catch(err)
 			 {
 			 
 			 }
 

The attribute “?callback?” is added at the last, to make the JSONP return. If we expect only the JSON object, then there is no need of the “?callback?” attribute.

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to call a Search API using REST using JavaScript from SharePoint Hosted App in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
April 15, 2015
 
Rate this article
 
Views
22412

In this article, let us see, how to create a simple SharePoint Hosted Application and make a REST API call using the JavaScript in SharePoint 2013.

Let us go with a step by step procedures.

1. Open the Visual Studio with “Run as Administrator”

image

2. On the New Project, Select “App for SharePoint 2013”

3. Give a Site Collection on which we want to deploy our App. I would suggest, for the development purpose, Give any of the “Developer Site” template.

image

4. Select the “SharePoint Hosted” on the dropdown and select “Finish”.

5. The solution will looks like as below.

image

6. Our App is going to get launched with this Default.aspx. If you closely look at that page, there is a reference for a file called “App.Js”. Actually this is the file which we are going to do most of our Activities.

7. As all of us know, that the SharePoint Hosted App cannot use any Server Side Coding. Hence, all the coding needs to be done by using JavaScript CSOM only.

8. That’s the reason, this App.Js is getting more importance.

9. Let us open App.Js and you can find the document.ready Event readily available for us.

10. There are certain functionalities by default written to show a sample for us.

11. We are not going to use them.

12. The App.Js looks like

 'use strict';
 
 var context = SP.ClientContext.get_current();
 var user = context.get_web().get_currentUser();
 
 // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
 $(document).ready(function () {
     getUserName();
 });
 
 // This function prepares, loads, and then executes a SharePoint query to get the current users information
 function getUserName() {
     context.load(user);
     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
 }
 
 // This function is executed if the above call is successful
 // It replaces the contents of the 'message' element with the user name
 function onGetUserNameSuccess() {
     $('#message').text('Hello ' + user.get_title());
 }
 
 // This function is executed if the above call fails
 function onGetUserNameFail(sender, args) {
     alert('Failed to get user name. Error:' + args.get_message());
 }
 

13. Now let me modify this App.Js as below. The Javascripts are self-explanatory.

 'use strict';
 
 var context = SP.ClientContext.get_current();
 var user = context.get_web().get_currentUser();
 var Results;
 
 // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
 $(document).ready(function () {
     //getUserName();
     showToolbar();
 });
 
 function showToolbar()
 {
     $("toolbarDiv").show();
 }
 
 function executeQuery(queryTerms)
 {
     Results = {
         element: '',
         url: '',
         init: function (element) {
             Results.element = element;
             Results.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryTerms + "'";
         },
         load: function () {
             $.ajax({
                 url:Results.url,
                 method: "GET",
                 headers: { "ACCEPT": "application/json;odata=verbose" },
                 success: Results.onSuccess,
                 error : Results.onError
             });
         },
         onError: function (error) {
             alert(JSON.stringify(error));
         },
         onSuccess: function (data) {
 
             var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
 
             $("#resultsDiv").append('<table>');
 
             $.each(results, function () {
                 $("#resultsDiv").append('<tr>');
                 $.each(this.Cells.results, function () {
                     $("#resultsDiv").append('<td>' + this.Value + '</td>');
                 });
                 $("#resultsDiv").append('</tr>');
             });
 
             $("#resultsDiv").append('</table>');
 
 
             
         }
     }
 
     Results.init($("resultsDiv"));
     Results.load();
 }
 
 // This function prepares, loads, and then executes a SharePoint query to get the current users information
 function getUserName() {
     context.load(user);
     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
 }
 
 // This function is executed if the above call is successful
 // It replaces the contents of the 'message' element with the user name
 function onGetUserNameSuccess() {
     $('#message').text('Hello ' + user.get_title());
 }
 
 // This function is executed if the above call fails
 function onGetUserNameFail(sender, args) {
     alert('Failed to get user name. Error:' + args.get_message());
 }
 

14. And the Default.aspx will be like

 <%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
 
 <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
 
 <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
 <%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
     <script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>
     <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
     <script type="text/javascript" src="/_layouts/15/sp.js"></script>
 
     <!-- Add your CSS styles to the following file -->
     <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
 
     <!-- Add your JavaScript to the following file -->
     <script type="text/javascript" src="../Scripts/App.js"></script>
 </asp:Content>
 
 <%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
     Page Title
 </asp:Content>
 
 <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
 
     <div>
         <p id="message">
             <!-- The following content will be replaced with the user name when you run the app - see App.js -->
             initializing...
         </p>
     </div>
 
     <div id="toolbarDiv" >
         <input type="text" style="width:200px" id="queryTerms" />
         <button onclick="executeQuery($get('queryTerms').value);return false;">Search</button>
     </div>
     <div id="resultsDiv">
 
     </div>
 </asp:Content>
 

15. With this we are ready to deployment. But before the deployment, make sure that our APP has appropriate permission to do a search. For that, on the AppManifest.xml file, the following permission level should be given.

image

DOWNLOAD THE SOURCE HERE

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment