Web API Using Power Apps Custom Connector

 

In this tutorial, we will discuss how to create ASP .Net Web application and use this web API in power app using custom connector.

1.     Create a new ASP .Net Web application project using Visual Studio

2.     Build, Deploy & Secure a Web API in Azure

3.     Connect API To Power Apps Using Custom Connector

 

1.     Create a new ASP .Net Web application project using Visual Studio

Open the visual studio 2019 and select ASP.NET web application (.Net Framework) and give the project name and click on Create.


On the next screen as shown below screen short select Web API and click on create.


Add a new empty controller to the project. Right click on the “Controllers” folder & select Add -> Controller -> Web API 2 Controller -Empty. Name this "ProductsController" as shown in below screen shorts.





The Project structure look like below format.


Next step right click on the “Models” folder & select Add -> cs file-> and name it as “ProductsControllers.cs”.

Add a new empty controller to the project. Right click on the “Controllers” folder & select Add -> Controller -> Web API 2 Controller -Empty. Name this "ProductsController"

public class Product

        {

            public int Id { get; set; }

            public string Name { get; set; }

            public string Category { get; set; }

            public decimal Price { get; set; }

        }

Update the following code inside the "ProductsController" class. It initializes a product array with necessary information and exposes two API operations (endpoints) that returns all products and a product by Id.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using static DemoWebAPICanvasapp.Models.ProductsControllers;

 

namespace DemoWebAPICanvasapp.Controllers

{

    public class ProductsController : ApiController

    {

        Product[] products = new Product[]

        {

            new Product { Id = 1, Name = "RICE", Category = "Groceries", Price = 1500 },

            new Product { Id = 2, Name = "Fish", Category = "SeaFood", Price = 500 },

            new Product { Id = 3, Name = "Fruits and vegetables", Category = "vegetables", Price = 100 }

        };

        public IEnumerable<Product> GetAllProducts()

        {

            return products;

        }

 

        public IHttpActionResult GetProduct(int id)

        {

            var product = products.FirstOrDefault((p) => p.Id == id);

            if (product == null)

            {

                return NotFound();

            }

            return Ok(product);

        }

    }

}

Our API returns will return the response as XML. We will modify the code such that the API returns response as JSON. In the "WebApiConfig.cs" add a new class as shown below.

public class BrowserJsonFormatter : JsonMediaTypeFormatter

        {

            public BrowserJsonFormatter()

            {

                this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

                this.SerializerSettings.Formatting = (Newtonsoft.Json.Formatting)Formatting.Indented;

            }

 

            public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)

            {

                base.SetDefaultContentHeaders(type, headers, mediaType);

                headers.ContentType = new MediaTypeHeaderValue("application/json");

            }

Resolve the reference errors by adding the following namespaces.

using System.Net.Http.Formatting;

using System.Net.Http.Headers;

using System.Web.Http;

using System.Xml;

 

In the "Register" function of the "WebApiConfig" class, add the newly created Formatter

config.Formatters.Add(new BrowserJsonFormatter());

Build and Run the app – Browse to the URL – http://localhost: {portnumber}/api/products You should observer the response being returned as JSON



2.     Build, Deploy & Secure a Web API in Azure

 

Now Let’s publish the app to Azure. Right click on the project and select "Publish".

Select Azure and Click on "Next".

 & choose Azure. and click on Next and choose "Azure App Service" as you publish target and click Next from Azure App service window Select "Create New". Also, choose "Create Profile" to modify the app service details.



On the next screen choose the “Azure App Service(Windows)" and click on next.


We need select the subscription name, Resource group and app service instance from azure, if you don’t have app service instance please crate new app service instance by clicking “+” as shown in below screen, after filling all  information click on finish and click on publish.



Currently we are having the API has anonymous access. We will now secure the API with Azure AD Authentication.

Login to the Azure Portal. Under "App Services", select the App service that we just provisioned above. Select "Authentication" and click on Add provider and in Identity provider as “sign in Microsoft and Azure AD identities and call Microsoft API’s” as shown in below screen shorts.





3.     Connect API To Power Apps Using Custom Connector

 

For Power Apps to access the secure API, we will need to register a client application in Azure AD.

Login to the Azure Portal and navigate to Azure Active Directory. In the left navigation select “App Registrations” and select “New Registration”.


Enter a name for your app and select the kind of accounts you want to give access to the API.

The types of accounts supported in this case, we select “Multitenant”. has we wanted to access our API in different tenant Leave the “Redirect Uri” as blank for now and click on “Register”.

From the “Overview” section make a note of the “Client ID” & “Tenant ID”. Keep this handy, we will need these details when we configure the custom connector.


Click on “API Permissions” from the left navigation and click on “Add a permission”. From the side pane that opens, search for your app & select the app.



In the “Request API permissions”, Choose the “Delegated Permissions” and select “user_impersonation”.

This will allow the client to access our API for the signed in user. Also, the user will be shown the consent form before accessing the API. Click on “Add permissions”.


Next we need to Generate  “Client secret” for the app.

From the left navigation select “Certificates & secrets”  under “Client Secret”, click on “New client secret”. Choose when you want the secret to expire from the available choice and click on “Add”.

The secret will be displayed only once. Note the secret ID  and keep it handy for later use as shown in below screen shorts for reference.


Let’s now create our custom connector in canvas app. Navigate to Power Apps. In the left navigation and Mouse over on customer connectors a pop will show at bottom we can see discover all click on that it will navigate to different screen, there in Data section we click on customer connector as show in below screens.



A new window will get open, on top right click on New custom connector and select create from blank.

On the next screen Fill the details under the “General information” tab in “Host” field, input the URL of the API without the scheme and click on security.


In “Security Tab” select API Key in authentication type and fill parameter label and parameter name, while connecting API to app we need to enter our clinet Id and Secret Id.

Click on “Create Connector” and Copy the “Redirect URL” that was auto-generated.

Navigate to the app we registered above for the client in the Azure Portal. From the “Overview” section. Click on “Add a redirect URI”.


Navigate to the app we registered above for the client in the Azure Portal. From the “Overview” section. Click on “Add a redirect URI”.

Under “Platform Configurations”, click on “Add a platform” and input the redirect URI that we had just copied.


Go back to the custom connector, under the “Definition” tab. Choose “Actions” and add a “New Action”. Input the details under “General” section as shown below. Note : The “Operation ID” will be the function that will be used in the Power Apps app.

Under the “Request” section, click on “Import from sample”. Select “Get” for the Verb & the URL will point to the “Products” endpoint. Click on “Import” as shown on below screen.


In the “Response” section, click on “Add default response” . For the “Body” field, specify the payload that you expect from the API for this request. Click on “Import”. Click on “Import”.


Finally we can test our customer connecter form test tab by selecting our connection as shown below.



Create a blank canvas app & add a gallery control to the screen. For “Data Source” click on Add data and search for our API “WebAPIGetProducts” and connect it.


Add gallery to our canvas app to display our items form API.

For the items property select “WebAPIGetProducts.GetAllProducts()” and in label property select thisItem.Category as shown in below screens.




























































 












Comments

Popular posts from this blog

How to implement approval in Teams using Adaptive Cards

Open canvas app with Customize the command bar using command designer

HTTP Request Methods

Create email templates in dynamic 365 and send email using Power Automate

Duplicate Detection in Dynamics 365 using power apps.