Call Azure Function From SharePoint Framework

Call Azure Function From SharePoint Framework

This Azure tutorial will discuss the Call Azure Function from SharePoint Framework.

Call Azure Function from SharePoint Framework

In this article, we will discuss two trendy topics: the Azure Function and the SharePoint Framework. We will also explain how to call the Azure Function from the SharePoint Framework (SPFX).

If you have some requirements to work with outside SharePoint, then Azure Functions is one of the best options.

What exactly will we perform here?

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

Create The Azure Function

Azure Function is a Microsoft Azure service that allows you to run pieces of code to perform tasks without worrying about the infrastructure for your application.

Well, Let’s 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 the Azure portal.

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

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

How To Create Azure Function Apps In The Azure Portal

Or, for the exact 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 is the time to create the HTTP-triggered Azure Function, since our Azure Function App is ready.

To create an Azure Function, click on the Functions link in the left navigation and then click the + Add button.

SharePoint Framework - Call Azure Function

Select the HTTP trigger template then Provide the name 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 next to the Test/Run button. Then copy the URL and keep it with you. We need to use that URL 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 which 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 details below

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 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 select the Y option, the webpart will be deployed to all sites. It’s 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 Web part or 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 different frameworks 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 issues.

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 the code space dot(.) command.

code .

Check the code now

You can see the solution that has been created below

Azure Function with SPFx

The next step is to Open the SpfxAzureFunctionWebPart.ts file, which is present “srcwebpartsSpfxAzureFunctionWebPart” path. and add the below import statement

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

It would be best if you mentioned the Function URL below

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

Add one IInfo.ts file in the “srcwebpartsSpfxAzureFunction” path. It should contain the below code

export interface IInfo {
    name?: string;
}

Now you need to add below import statement below to the SpfxAzureFunctionWebPart.ts file, which is present “srcwebpartsSpfxAzureFunctionWebPart” 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 at the starting of the article to create an Azure Function App. Below is the Azure Function App that I have created.

Azure Function, Connect To SharePoint

Now, Our Function App is ready, 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 see my Azure Function project is ready now as shown below

Delete SharePoint Online List From Azure Function App visual studio 2019

Now, You can use the code below 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 was deleted successfully

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 we created above, click on the functions option from the left side, and click on the Function we published just now.

Click on the Get function URL button 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 see below that the SharePoint list was deleted successfully

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 provide the Function name 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 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 two below dlls and drag them to the folder

image 8

Now navigate to the Azure Function again and click on the Code + Test link 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 click on the Get Function URL button copy that and append the title value like above and access from your browser to see the expected output.

You may also like to follow the below articles

Wrapping Up

Well, in this article, We discussed Call Azure Function from SharePoint Framework. I hope you have enjoyed this article !!!