Call Azure Function From SharePoint Framework

Call Azure Function From SharePoint Framework

In this Azure tutorial, we will discuss Call Azure Function from SharePoint Framework. Along with this, we will also discuss a few other topics like Create The Azure Function, Set Up CORS on the Azure Function, Create SharePoint Framework Webpart, Azure Function, Connect To SharePoint, Delete SharePoint Online List From Azure Function App, etc.

Call Azure Function from SharePoint Framework

Well, in this article we will discuss, Two trendy pieces of stuff, Yes we will discuss the Azure Function as well as SharePoint framework. As part of this article, we will discuss, How to Call the Azure Function from the SharePoint Framework (SPFX).

If you have some requirement to work with out side SharePoint, then Azure Function is one of the best option to use.

What exactly we will perform here ?

  • We will create an Azure HTTP triggered Function.
  • The next step is we will see How to consume the Azure Function from the SharePoint Framework Client WebPart.

Create The Azure Function

Azure Function is an Azure Service from Microsoft that helps you to run some pieces of code smoothly to perform some tasks without getting worried about the infrastructure for your application.

Well, Lets create an Azure HTTP triggered function using the Azure Portal. Follow the below steps to create the Azure Function

Follow the below steps to create Azure functions in Azure portal.

Step-1: Login to Azure Portal (https://portal.azure.com/)

Step-2: As highlighted below, click on the  + Create a resource, click on “Compute”. Now, choose the “Function App”.

How To Create Azure Function Apps In The Azure Portal

Or, for the same Option, you can search for the Function App and click on the search result.

Azure Function Creation using Azure Portal

From the next step onwards, You can follow my article to create the Azure Function App using the Azure Portal to create the Azure Function App. Assuming Your Azure Function App is ready.

Now the time to create the HTTP triggered Azure Function, since our Azure Function App is ready.

Click on the Functions link from the left navigation and then click the + Add button to create the Azure Function.

SharePoint Framework - Call Azure Function

Select the HTTP trigger template and then Provide the name and choose the Authorization level as Anonymous and then click on the Create Function button.

Call Azure Function from Sharepoint Framework

Below is the default code for my Azure Function app

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{ log.LogInformation("My Azure function processed a request.");    
    
    string name = req.Query["name"];    
    
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();    
    dynamic data = JsonConvert.DeserializeObject(requestBody);    
    name = name ?? data?.name;    
    
    return name != null    
        ? (ActionResult)new OkObjectResult(new { name = $"Hello, {name}"} )    
        : new BadRequestObjectResult(new { name = " name you need to pass on the query string or request body"});    
}

You can see the same here

call azure function from spfx webpart

Now Just to make sure the Azure Function is working fine, you can click on the Test/Run and then Provide the value for the name parameter in the body and click on the Run button. You can able to see it ran successfully for me and I got the perfect Response Code.

spfx call azure function

Now click on the Get Function URL button, which is next to the Test/Run button. Then copy the URL and keep it with you. That URL we need to use it in our code next. I have copied the URL and it is like below

https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger

SahrePoint Framework Call Azure Function

Set Up CORS on the Azure Function

Open the Azure Function App that you have created above and then click on the CORS from the left navigation and then provide the local host URL and  Office 365 tenant domain URL and then click on the save button.

How to call Azure Function from SPFX

Create SharePoint Framework Webpart

Now that our Azure Function part creation is over. This is the time to create the SharePoint framework webpart. Follow the below steps to create the SharePoint framework webpart.

The first step is to create a directory, in that we are going to create the project. For that, Open the command prompt and run the below command to create the directory

md spfx-azure-function-demo 
Create SharePoint Framework Webpart to call Azure Function

Navigate to the spfx-azure-function-demo directory using the below command

cd spfx-azure-function-demo

Now the next step is to create the solution, Run the Yeoman SharePoint Generator to create the spfx web part solution. Execute the command as mentioned below.

yo @microsoft/sharepoint

Now it will ask you to provide the below details

SPFX webpart to call the Azure Function

What is your solution name?: You can type a solution name or if you want to keep the default name, you can just hit the Enter.

My Selected Value: Just Hit Enter

Target environment: You need to select the environment where the webpat will deploy.

My Selected Value: SharePoint Online only (latest)

Where do you want to place the files?: Where you want to keep your files. You can either choose the current folder or you can also create a subfolder under the Project folder.

My Selected Value: Same folder

Deployment option: If you will select the Y option then it will deploy the webpart to all the sites. Better to select the N option here.

My Selected Value: N

Which type of client-side component to create? You can create the webpart or Extension.

My Selected Value: Webpart

Name of the Webpart: You need to provide a name for the webpart.

My Selected Value: SPFXAzureFunction

What is your Web part description? You can type a description for the webpart or You can hit the Enter button to keep the default description.

My Selected Value: This webpart will call the Azure Function

Which framework would you like to use? You can use a different framework like No JavaScript Framework, React, and Knockout. You can choose the No JavaScript Framework.

My Selected Value: No JavaScript Framework

You can able to see below, all my provided options to create the SPFX client side webpart

How to create SPFX webpart to call the Azure Function

Now Yeoman generator will start creating the solution based on the input provided above. Now you can able to see the solution has been created successfully without any issue.

How to call Azure Function from SPFX webpart

Now To lock the version of the project dependencies, you can run the below command

npm shrinkwrap

Now, to open the code editor, type code space dot(.) command.

code .

Check the code now

You can able to see the solution that has been created as below

Azure Function with SPFx

The next step is Open the SpfxAzureFunctionWebPart.ts file which is present “\src\webparts\SpfxAzureFunctionWebPart\” path. and add the below import statement

import { HttpClient, SPHttpClient, HttpClientConfiguration, HttpClientResponse, ODataVersion, IHttpClientConfiguration, IHttpClientOptions, ISPHttpClientOptions } from '@microsoft/sp-http';  

You need to mention the Function URL like below

protected functionUrl: string = "https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger";    

Add one IInfo.ts file in the “\src\webparts\SpfxAzureFunction\” path. It should contain the below code

export interface IInfo {
    name?: string;
}

Now you need to add below import statement to the SpfxAzureFunctionWebPart.ts file which is present “\src\webparts\SpfxAzureFunctionWebPart\” path. and add the below import statement.

import { IInfo } from './IInfo';

Below is the code for my RetrieveAzureFunction() function.

export default class SpfxAzureFunctionWebPart extends BaseClientSideWebPart <ISpfxAzureFunctionWebPartProps> {
  protected functionUrl: string = "https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger";
  protected RetrieveAzureFunction(): void {    
    const requestHeaders: Headers = new Headers();    
    requestHeaders.append("Content-type", "text/plain");    
    requestHeaders.append("Cache-Control", "no-cache");    
  
    var siteUrl: string = this.context.pageContext.web.absoluteUrl;    
    var firstname: string = (<HTMLInputElement>document.getElementById("txtFirstName")).value;    
      console.log(`SiteUrl: '${siteUrl}', FirstName: '${firstname}'`);    
      const postOptions: IHttpClientOptions = {    
      headers: requestHeaders,    
      body: `{ name: '${firstname}' }`    
    };    
      let responseText1: string = "";    
    let result: HTMLElement = document.getElementById("responseContainer");    
      this.context.httpClient.post(this.functionUrl, HttpClient.configurations.v1, postOptions).then((response: HttpClientResponse) => {    
       response.json().then((JSONresp: IInfo) => {    
          
          if (response.ok) {    
              //Write something here;    
          } else {    
              //Write something here;    
          }    
  
          result.innerText = JSONresp.name;    
        })    
        .catch ((response: any) => {    
          let err: string = `Error calling URL ${this.functionUrl}. Error = ${response.message}`;        
          console.log(err);    
          result.innerText = err;    
        });    
    });    
}    

The code below is my Render() method.

this.domElement.innerHTML = `   
    <input type="text" id="txtFirstName"></input>    <br/>
    <button id="btnRetrieveAzureFunction" >Hello</button>     
      `;    
    
      document.getElementById("btnRetrieveAzureFunction").onclick = this.RetrieveAzureFunction.bind(this);

Run the SharePoint Framework Webpart

Now in your command prompt run gulp clean, gulp build and then finally, gulp serve

Navigate to the Sharepoint workbench i.e https://your SharePoint site/_layouts/15/workbench.aspx and add the webpart.

Provide a first name in the text box and then click on the Hello button, It will show you the expected Output.

This is how you can create SharePoint Framework – Call Azure Function.

Azure Function, Connect To SharePoint

As part of this functionality. We will create an Azure Function App to delete a sharepoint list using CSOM.

Delete SharePoint Online List From Azure Function App

The first step is to create An Azure Function App using the Azure Portal

Follow the above-mentioned steps that we have discussed already on the starting of the article to create an Azure Function App. Below is my Azure Function App that I have created.

Azure Function, Connect To SharePoint

Now, Our Function App is ready, now we will create our Azure Function. We will create that using Visual Studio 2019.

So, Create the Azure function using Visual Studio 2019 now. You can able to see my Azure Function project is ready now as below

Delete SharePoint Online List From Azure Function App visual studio 2019

Now You can use the below code for your Azure Function

using System;
using System.IO;
using System.Threading.Tasks;
//using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
//using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.SharePoint.Client;
using System.Net;
using System.Net.Http;
//using Microsoft.AspNetCore.Mvc.WebApiCompatShim;
using System.Linq;

namespace deletesplistvs
{
    public static class Function1
    {
        [FunctionName("NewFunction")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage request,
            ILogger log)
        {

            string site = "https://tsinfo.sharepoint.com/sites/SPFx/";
            string userName = "test@tsinfo.onmicrosoft.com";
            string password = "####@12345";


            // parse query parameter  
            string listtitle = request.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "title", true) == 0)
                .Value;


            System.Security.SecureString secureString = new System.Security.SecureString();
            foreach (char ch in password)
            {
                secureString.AppendChar(ch);
            }

            SharePointOnlineCredentials creds = new SharePointOnlineCredentials(userName, secureString);

            using (var ctx = new ClientContext(site))
            {
                ctx.Credentials = creds;
                List lst = ctx.Web.Lists.GetByTitle(listtitle);
                lst.DeleteObject();
                ctx.ExecuteQuery();
                return lst == null
                ? request.CreateResponse(HttpStatusCode.BadRequest, "Error retreiveing the list")
                : request.CreateResponse(HttpStatusCode.OK, "List Deleted successfully " + listtitle);
            }
            return null;
        }
    }
}

Make sure to make the below changes to the projectname.csproj file

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <AzureFunctionsVersion>v1</AzureFunctionsVersion>
  </PropertyGroup>

You can test it locally. Press F5 and then copy and paste the function URL with title value as a query string parameter like below

http://localhost:7071/api/NewFunction?title=testlist

You can see the list deleted sucessfully

Delete SharePoint Online List From Azure Function

Now right click on the solution and click on the Publish button

Select the existing option from the next window and then choose the Azure Function App that we have created above and click on the Ok button.

How to Delete SharePoint Online List From Azure Function App visual studio

Now click on the Publish button to Publish the Azure Function to Azure

How to Delete SharePoint Online List From Azure Function visual studio 2019

Now log in to the Azure Portal and navigate to the Azure Function App that we have created above, click on the functions option from the left side and click on the Function that we published just now.

Click on the Get function URL button and copy the URL and keep it. The URL should be like below

https://connecttosharepoint12.azurewebsites.net/api/NewFunction?code=Ywz0yHIlFxol2BqaZDdC5xLvyESRffgCTPh5mqLyyZ/UutI0n0vebQ==

How to Delete SharePoint Online List From Azure Function

Now open your favorite browser and pass the title value along with the query string parameter. testing is the name of my list.

https://connecttosharepoint12.azurewebsites.net/api/NewFunction?code=Ywz0yHIlFxol2BqaZDdC5xLvyESRffgCTPh5mqLyyZ/UutI0n0vebQ==&title=testing

You can able to see below, the SharePoint list is deleted sucessfully

Delete SharePoint Online List From Azure Function CSOM

You can also able to delete the SharePoint list from the Azure Portal

Delete SharePoint Online List From Azure Function App using Azure Portal

Our Function App is ready now, Let’s create the Azure Function now. You can again follow the steps mentioned above to create the HTTP triggered Azure Function. You can choose the HTTP trigger template and provide the Function name and choose the Authorization level as Function and click on the Create Function button to create the Azure Function.

image

Now the Azure Function is created as below

image 1

Now Navigate to the Azure Function App, click on the Advanced Tools link from the left navigation, and then click on the Go button.

image 2

Click on the CMD option from the Debug console drop down.

image 3

Click on the site folder.

image 4

Now you can click on the wwwroot folder.

image 5

You can able to see the function name, you can click on that

image 6

Click on the + and then New folder and you can name it to bin.

image 7

Now you can download below two dlls and drag it to the folder

image 8

Now navigate to the Azure Function again and click on the Code + Test link and you can use the below namespaces and the code from the above

#r "Newtonsoft.Json"
#r "Microsoft.SharePoint.Client.dll"  
#r "Microsoft.SharePoint.Client.Runtime.dll"  
  
using System.Net;  
using Microsoft.SharePoint.Client; 

Now if you will click on the Get Function URL button and copy that and append the title value like above and access from your browser to see the expected output.

You may also like follow the below articles

Wrapping Up

Well, in this article, We discussed Call Azure Function from SharePoint Framework, Create The Azure Function, Set Up CORS on the Azure Function, Create SharePoint Framework Webpart, etc.. We have created an Azure HTTP triggered function and then we have created an SPFX client webpart. Then finally, we called the Azure Function from the SPFX webpart. We also discussed Azure Function, Connect To SharePoint, Delete SharePoint Online List From Azure Function App, etc. Hope you have enjoyed this article !!!