Showing posts with label Custom Connectors. Show all posts
Showing posts with label Custom Connectors. Show all posts

Wednesday 6 September 2023

App Insights for Power Platform - Part 11 - Custom Connector

Overview:  Power Automate can set retry policies on custom connectors, Canvas apps using a Custom Connector, does not have any retry configuration.  FYI is the Custom Connector gets a 5.x.x error it shall retry 4 times.  Proven using 500 and 502 errors.  408 (timeout) and 429 (to busy) errors appear to throw 4 times (retry driven by canvas app; using the Custom Connector trigger shall only try once).  

My example:  My Canvas app uses a custom connector, that calls my Azure Function, in turn this calls my APIM, and APIM calls the 3rd party.


My Azure function returns a 500 or 502 or 408 (response timeout) or 429 if the response has not been received in 10 seconds, and I push the http code back to the Custom connector.  I can see the response from the 3rd party is taking +-35 seconds.  I can see from network traces 4 invoked calls that all fail with 408 http response codes.

Result:  The custom connector retries 4 times resulting in my Power App being locked for 40+ seconds.

Possible remediation

1. Return a 418 HTTP response code (I am a teapot), my app calls the function using the custom connector once.  So using 418 (also tested with 400 - but 400 is not the right response) errors behaves differently from the 5xx, 408, 429 errors from the API.  

Note: Originally I was caught out as I trigger using the custom connector test rig, this only tries once.  But when called from Power Apps, it shall try four times.  Returning 408 is not a fix.  Returning 418 ensures I only try once, get a better user experience and now I have 418 logs that I add error details to.

2. 3rd party API should not take 35 seconds, improve it.  

3. I could set my timeout on the specific function to 40 seconds, however if the call starts going to 41 seconds, my canvas app will be locked for over 160 seconds.  

4. Go to all API's and if they are fast set the timeout as short as possible so the app does not get locked out while waiting for the 4 responses.

Summary: Examine the 3rd party API's, get them stable and performant and per the agreed SLA's.  If you only want to try once ensure that time outs on the 3rd arty are set to the SLA or if you intercept the request, you can choose the timeout, by examining the API's you can see the optimum time to avoid timeouts and using the 418 response code, the call only happens once.

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern (this post)

Monday 28 August 2023

App Insights for Power Platform - Part 10 - Custom Connector Logging Thoughts

Overview: One of our developers was asking about a log he was struggling to trace, and it took me awhile and a lot of help from the community to truly understand the issue.  My scenario is shown below:


Scenario: I have a Dataverse change triggering a flow, the flow calls a Custom Connector, that in turn calls an Azure Function (that I control).  So the flow fails, and I have used a pattern in the flow to catch the error and log it into Log Analytics.  All good, then I don't see the event where the action calls the function, my function has logging enabled.  I can see I am getting a 401 unauthorized error.  

Initial Hypothesis: The Power Platform use APIM internally to implement Custom Connectors, and there is no access for clients/tenants to see the internal logging/traffic.  Microsoft have provide the ability to use iLogger on the custom connector to log the traffic.  

We have flows that intermittently get a 401, when the flow is manually rerun, the flow works and I can see the traffic coming into the Function.

The failure rate is extremely low and retries almost always fix the issue, and a third try always ensures the transaction goes thru.

Resolution:  Add logging to the custom connector so we can speak with MS support about the issue.  Add alerting to notify support, they can contact the user or chose to rerun the flow. 

Alternative: If I  enable the code, I can override the behaviour and inject C# code to work with the backend, or handle logic such as replacing text,... 

1. In step "4. Code" tab of the custom connector, add the code below:

You can do any C# logic, I'm sending the original request thru and if it doesn't return me a 200, I'm logging it as critical. 

2. Update the connector, go to the next step "5. Test" > "Update Connector" (Tip: follow the steps)

3. Run the "Test operation", open the Response and validate the response body is correct, then open the "Code logs" tab.  If it is blank, re-run the "Update Connector" (irritating but true). 

304 return from the API, which is cached and not a problem, but 400, 500 would be an issue, could also look out for 429s.

Full C# Code:

public class Script : ScriptBase

{

    public override async Task<HttpResponseMessage> ExecuteAsync()

    {       

        this.Context.Request.Method = HttpMethod.Get;

        HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(continueOnCapturedContext: false);

        Context.Logger.LogTrace("Custom Connector ListBooks called "); 

        if (response.StatusCode == HttpStatusCode.OK)

        {    Context.Logger.LogTrace("Success");      }   

        {    Context.Logger.LogCritical("Critical | " + response);     }

        return response;

    }

}

More Info:

https://learn.microsoft.com/en-us/connectors/custom-connectors/write-code (NB)

https://never-stop-learning.de/logging-in-custom-connector-code/ (NB) The 2nd part of this post on the Alternative , is a rehash of this amazing post - I amended the logic and now I'm wondering is I could write to App Insights using the SDK?

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging (this post)

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern


Tuesday 6 December 2022

Using the OpenAI PowerFx language helper leading into building a Tax chatbot using Power Apps (No model training)

I had some time today, and I've been hearing a lot about OpenAI/GPT-3, so I thought I'd have a look around and wow it's good.  There are so many uses and it's just easy to use.

For instance, Power Apps uses PowerFx which is a simple language that Microsoft had added the "Ideas" are to that helps you build PowerFx code.  Honestly I found it extremely irritating when it was released recently but after reading more on Open AI I to take a closer look and it definitely is a great idea.



Thoughts:  I don't memories code so I feel this is a great tool for citizen and professional developers.  I think it will get a lot of attention and improve over time and become a key part of PowerFX and app development.

More Info:

https://learn.microsoft.com/en-us/power-apps/maker/canvas-apps/power-apps-ideas

OpenAI - Took less than an hour to setup the demo

The Power Platform has a Premium Connector to use the OpenAI API's.  Robin Rosengrun has a demo and built and published a connector. 

I spent some time playing around with the OpenAI GPT-3 API using the "davinci-002" engine in a Power App connector.    

First search data result is correct
This is completely wrong, although HMRC have amended the go live date many times.  I was hoping for "6 April 2024"

The third question result is good - but could be better.

Saturday 17 September 2022

Generating a Canvas App from a Custom Connector (Open API)

Overview: The Power Platform CLI in August was updated and 1 of the new features is the ability to use the CLI command line to generate a Canvas app using an Open API as the data source.

The Power CLI supports the GET and POST endpoints.  Which is normally +85% of the endpoints anyway.  

In this post I walk thru the steps to add books using an Open API and retrieve all the books as well as the new book added.  

Solution

1. I used the free postman API endpoints (2 gets and a post) > Exported the collection

2. In Power Apps > using a Solution > Add a new Custom Connector (tip: I used Automate)> Upload from a Postman Collection > Pass in the Postman collection generated in the last step.   Save the Custom Connection as shown below.  Lastly test the Custom Connector.
3. I used Visual Studio code with the Power Platform Extension
Using the Power Platform CLI, in the terminal run ps> pac to verify the Power Platform extension is available.

// Get the environment you want to work on
ps> pac admin list

// Get the Custom Connector Name or Id you are going to base the Canvas app on
ps> pac connector list --environment a9adbbba-c45d-eac1

// Generate the msapp package
ps> pac canvas create --msapp "C:\Radimaging\BookDemo.msapp" --connector-display-name "BookDemoCN" --environment "a9adbbba-c45d"


4. Import the export Power App.  Select your environment, and create a new Canvas driven Power App.  "Open" has recently changed in the UI.


The app will get created, I had to add the Custom Connector to the App and you are ready to customise

Beware: Custom Connectors and Connection References in Managed Solutions.  It's a good idea to check they work in the deployment pipelines as the rework can be a pain.  

Summary: This is a great way to build an application quickly using the pac create.  It is a bit rough, and needs amending after import on the 3 endpoints I've used but a great start to a new feature. 

Wednesday 18 August 2021

Creating a Power Platform Custom Connector from a Postman Collection

Problem:  I like to discover an API and play with it using Postman.  I save the collection and theoretically I should be able to upload the postman collection into the custom connector to generate the Power Platform connector.  Until a few days ago, the custom connectors only supported Postman v1.0 collections.  And Postman has not save using the v1 format for a long time.  

I was happy to see the Custom connectors support v2.0 and 2.1 of postman collections.  Only problem is while it says it does if is still broken.  So I have to go the old school way.

I wanted to generate custom connectors for HMRC's REST API so that I can connect with the Power Platform.  Option 2 below gives me a way to build my collections using HMRC's API's and generate the appropriate version 2 Swagger definition.

Resolution

Option 1: 

  1. Export the postman collection in v2.1
  2. Upload the postman file to https://apitransform.com/ and generate the OpenAPI specification (version 3.0.0) gets generated.
  3. Upload the OpenAPI 3.0.0 specification file to Transformer | APIMatic and generate the JSON Open API 2.0 version.
  4. In Power Apps add a new custom connector based off the Open API file (version 2.0) to generate the connector.

The process is a pain, but this approach does not need any software installed.  I do feel Power Platform are about to improve by accepting the Postman v2 collections and it would be great if it could read Open API file in YAML and JSON in both V2.0 & 3.0 but any of these permutations would be a game changer.

Warning: Large collections end up with information being lost in the translations.

Option 2: 

  1. Export the postman collection in v2.1
  2. Upload the Postman 2.1 Collection file into Transformer | APIMatic and generate the JSON Open API 2.0 version.
  3. In Power Apps add a new custom connector based off the Open API file (version 2.0) to generate the connector.

Saturday 5 September 2020

Reducing Power Apps Dynamic calls and where to store Power Apps data.

Overview:  Power Apps is driven by data and generally that data comes from Connectors.  So the great news is there are a lot of different connectors and if in trouble I always find the custom connector can be relied upon.  When working with Power Apps, it is not as simple as just having a data source and consuming it, one needs to consider all the data sources, do we need live data, performance.  Basically, going and dynamically pulling lots of dynamic sets of data repeatedly leads to poor performance.

CDS performance has relatively few layers when retiring or updating data so it generally is fast to work with.  Custom connectors have more layers so can be slower and you are dependent on the underlying REST API so watch for performance.  The on-prem azure data gateway is pretty slow but amazing if you need it.

Identify data sources:  CDS, Azure SQL, SharePoint SQL on-prem., CosmosDB, RSS, Open API's...

Understand the security, and the amount of data being pulled.  For example, if we need all the airport codes in the world for a drop down so the user can choose their closest airport e.g. JFK is for New York John F Kennedy airport.  There are roughly 4000 commercial airports in the world. 

Options: Call an Open API service.  Power App by default returns sets of 500, Power Apps max return count is 2000.  You still need to perform 2 calls with paging to get the full data set.  You could use a type ahead if the API supports it, but their will be a lag after each keystroke when Power Apps runs out to the service.  And there will be a lot of calls.  More suitable would be to do 2 calls with 2,000 record for each call and bind the control to the returned data.

A further improvement would be to store the airport lookup on data load or on first request, then subsequent requests would use the table/collection.  In effect, you are locally caching all the airport codes using 2 calls for each Power Apps user session.

For the airport example, one could also store the data using a Excel import, but beware the data is imported into Power Apps and store locally.  Big issue is the data is static in Power Apps, to update it, you need to re-import the Excel table.  So brilliant for sat days of the week or Months of the year as these never change.  Fairly static data like airport codes work well, but require a publisher level overwrite to update the list.  Also, storing extreme amounts of static data leads to bloat of the app and that data still needs to be loaded.  So I would not consider it for 100k+ items as a general rule.  

FYI Microsoft recommends to use less than 30 connections per application.

More Info:

Todd Baginski has a great video on using Excel import and creating language variations/multi-lingual Power Apps using Excel imports.

Alagunila Meganathan on C# Corner has a good post on Excel Imports for Power Apps.


Sunday 1 March 2020

Power Automate Notes

What is Power Automate?
Power Automate previously called Flow.  Power Automate contains "Flows".  Power Automate is workflow including RPA options, refered to a Power Automate Desktop (PAD).  Power Automate is a workflow engine that is based on Azure Logic Apps.  Powerful extendable workflow solution for low code automation.  Allows workflows to be easily automated with 3rd part systems e.g. SAP.

Used for:
  1. Personal Workflows e.g. I send an email to all people that have not update the DevOps Scrum board on a in the last day as a scrum master.
  2. Business Process e.g. Holiday request form.  If more than 10 days, need senior manager approval.  Generate RFP based on an event.  Historically, used K2 or Nintex or WCF workflows for business processes.
  3. Integration: e.g., move twitter posts into my warehouse for data-mining later.
A key concept is who shall the flow run as, a user or a service principal.  Setup a Service Principal in Power Automate » Benedikt's Power Platform Blog (benediktbergmann.eu)

Flows run against the owners account for calculating allowable usage (default), it is common practice to use a service account (normal AAD account with user and Pswd) to own specific flows.  A service account is a normal user account from AAD/Entra's perspective.  A dedicate account ensures that when a specific user leaves your business, the flow continues to run.
Img 1. Usage limits in Flows are counted against the flow owner.



Agree Power Automate Standards:
  1. Flow Names: start with a verb  format: Verb + What the Flow does + (trigger) e.g. "Get Tax Rates (Instant)".  I like to also prefix with the Company and Project, but feel free to have a standard to suit your business.  e.g. EY-USTax Get State Taxes (Instant) or EY-USTax Get All US State Tax Rates (Scheduled) or Get SalesForce Data.  Optional, for project specific workflows I also prefix witht he project name e.g. USTax-GetTaxRate. 
  2. Description: Short description to help readers understand what the flow does.
  3. Actions: Leave the Action desc and add info e.g. Compose: Tax Note.
  4. Variables: prefix with "v" e.g. vTaxTotal in camelCase.  e.g. vUserAge.
  5. Error handling & Logging: Catch errors and log into to App Insights via an Azure Function or Log using the built in Azure Log Analytics Action.  More logging means better traceability.
  6. Scope: Add scope actions for try catch logic.  Add multiple actions inside a "Scope" Action
  7. Terminate the flow with the Terminate Action if the flow has failed.
  8. Environment Variables: Great for logging as I go thru DTAP.  Also see.
  9. Connection Reference Name: Agree a format, does this flow run as  user or as a specified user.
  10. Loop Sparingly, use First() for performance.
  11. Owner: I like to use a service account in dev, it's a good idea to add tech owners as when it needs updating to support and easily find who they should talk too.  Understand who you are running the flow as, this ties to licencing but is critical.  You need to know you Actions and licencing limits on a project.
  12. Comments:  Im not a huge fan as the naming should make most flows make sense/self documented, but for tricky logic, comments are great.  Agree a standard.
  13. Retry policy: What happens if an action fails, do you want to try again?  
I borrowed a lot of the standards from "Matthew Devaney"
I found this document later - it is excellent. by Prasad Athalye - Best Practices for Power Automate(Microsoft Flow) Development

Licencing:
  1. Seeded licence is part of O365.  Use standard functionality such as standard connectors without needing to pay more for advance.  The advance/premium connectors are not part of the O365 licence.
  2. Per User licence -  Allows the  user $15 retail, can get discount with bulk and can use the advanced connectors & on-prem. gateway.  Many users need multiple workflows, normally personal workflows.
  3. Per User RPA licence - same as above but also has amazing RPA capabilities.
  4. Per Flow/Process - $100 per process per month, min 5 flows per month licences.  Anyone can use as part of the process.  Use for few people but process does a lot of workflows.  Can add a process one at a time after the first 5.
Licencing MS page
Power Automate has some licence add-ons available: AI builder and an unattended RPA add-on.
"Power Apps licenses will continue to include Power Automate capabilities", I don't know what is included but I assume it means any connector I can use in Power Apps, assuming I'm in Power Apps I can make Flows for.

Build workflows:
  • Can get a dedicated IDE tool for Power Apps or use the browser (which i always use).
  • There are over 350 connectors (in both standard and premium) and you can always use a custom connector to any OpenAPI (Swagger) endpoint.
  • Templates have some examples and often help as a starting point to make your own custom Flows in Power Automate.
  • Easy clear tracing so you  can see what part of the workflow is working and where you fail, and you can drive into the issue.  Super easy to use.
  • Example of an Instant Cloud flow triggered by a canvas Power App...

Query a Dataverse table in a Flow using OData

ParseJSON is fantastic for converting Open API/OData/JSON into an object

Extending - break out for programmatic control, I use C# Functions from my Flows and call them via HTTP triggers.
Retrieving  a row from the Dataverse custom "Subject" table.

Robotic Process Automation (RPA):
  • Also known as UI Flows within Power Automate.  Microsoft have purchase and integrated Softomotive for UI flows to add WinAutomation.
  • Attend (user logged in) and unattended version (complete tasks without manual intervention)
  • Can have multiple instances
  • API is generally better than using RPA as it is versioned and generally not changeable, whereas using a website, they website can be changed causing the RPA flow to fail.  Useful for instance when the RESP API is incomplete.
  • Recording tool for creating UI flows - Web use Selenium to record.
  • 3 Types: 1) Windows /Desktop/Screen reader and 2) web/website (Selenium) and 3) WinAutomation (covers both Windows and Web, easy to use but not as full featured yet).
  • WinAutomation has a drag and drop IDE, has error handling.
  • UI flows are well priced.  Also get AI builder credits with UI flow licences.
  • "Power Automate Per user plan with attended RPA to use UI flows and WinAutomation" Microsoft.
AI Builder:
Cognitive builder e.g recognize forms and extract data. E.g. receive invoices and add to accounting SaaS software.

Other: Zapier is a good tool for end user automation.  Easier than Power Automate but not as structured.  I'd use Zapier to automate in small businesses without O365 or flow licencing and allow end users to do it themselves.

Problem Solving:

Problem:  Another developer created a Flow I need to use from a Canvas page inside a model app.  The Flow is showing up when i say add but i get the error "Unable to add flow"
Initial Hypothesis: The flow is owned by another developer having ownership and the connection is done thru their account, take ownership and change the Connection (Dataverse connection in my case)
ResolutionTo use an existing flow, you need: 1) flow in same solution as the canvas app, 2) Ownership and the connection string needs to be switched to the new developer

Problem: Migrating solutions between environments, all the workflows fail when they use the Dataverse connector with 403 errors. Tracing the flows, I can see the error  "Flow client error returned with status code 'BadRequest' and details {error: code: 'XrmApplyUserFailed... UserNotinActiveDirector ... does not exist in user tenantId"
Problem: Using the service Principal account needs to be registered in the new Dataverse environment.
The connector issue was fixed, we had to recreate the connection from scratch making sure it was set up with a/the service principal. Then we added the registered app into the environment as an application. user.


Wednesday 12 February 2020

Power Apps - DTAP Azure diagram

Overview:  A sample architecture for DTAP in a highly controlled environment.  There are a lot of variations and the ability to use Power Apps publishing.


There are a few ways to manage environment deployments.
  1. Simple: Create in unmanaged solutions and Export and Deploy Managed solutions manually using the Power Platform Ux.
  2. Enterprise: Build Azure DevOps pipelines to add unpacked code to Github and deploy solutions using Azure pipelines.
  3. 3rd party ALM tooling, some is specific to Dynamics.
  4. Nov 2022 - Microsoft announce Power Platform Pipelines 

Custom Connectors:  As you step thru the DTAP environments using ALM to deploy you need to point the custom connector to the appropriate APIM (API):
Environment Variables are extremely useful for ALM


Sunday 19 January 2020

Power Apps Quick Tips

Some of my Power Apps notes:

Licencing:
Determine your Power Apps licence using Power Apps Web user interface:
Power Apps > Settings > Plans

Note:  Microsoft changed how Power Apps licencing works circa Nov 2019.  The Power Apps licence with O365 E3/E5 does not have the connectors so is useful only for simple apps, and using flow, the apps can get more advanced.

Testing:
I saw a preview of the Power Apps Test Framework as the Microsoft Ignite Tour in mid Jan 2020.  The framework allows for recording UI tests and inserting asserts.  The tests are stored alongside the project inside Power Apps.  PowerApps Testing is in beta, it will be release by region so presumably it's already available in some US regions on the public beta.  The CI/CD pipeline integration was not shown but I'm sure some smart fella will look at this shortly.  I'd use Selenium for automated web testing at this stage, but that may change especially for mobile app development.

Updated 28 Jan 2020: Test Studio for Power Apps released today.  Here is the announcement.  Here is another recording outlining testing of Power Apps.

In the Power App > File > Settings > Advanced Settings > Scroll down to "Formula-level Error Management" and turn on the feature.
Open the "Advanced tools"
Accessing Test Studio in Power Apps


Power Apps Development Standards:
Error Handling - Should an unexpected event occur, log so the issue can be traced, as of 3 Feb 2020, PowerApps has App Insight integration.
Naming standards - Label visual controls and variables
Approved Colours - Digital branding standards
Reuse - Control reuse with shared branding
Roles - AAD connector allows me to figure out the user group the current user belongs too so they get appropriate menus, screens, and actions.
Menus -  @Laura-GB https://www.youtube.com/watch?v=5G-gVWRItmc  Build a menu component, input allows one to combine with AAD roles to create dynamic menus for users.
Copy and pasting OOB controls - such as a textbox, if you use a formula, the values are persist and passed around.  So if you have a color set by a variable, copy and paste results in the new text box referencing the colour.  Taking this further, if you put in the position X and Y a formula e.g. X=66*1 and Y=100*1, the control will inherit the parent controls property rather than reset the property.

Steps to setup and Use a Custom Connector:

Get the http response from a custom connector and add to a collection
Common Functions:
DateTimeValue() - Convert string into a date
Text() - Format a string
Value()- Format a string into a numeric
Text(DateTimeValue(TextInput1.Text), "dd-mmm-yyyy")
An approach I like to advanced Power App Input Validation.
Lookup() - Finds the first record in a table, closely related to Filter() and Search()
I.e. Fx> Set(Lookup(<DataverseTblName>,<UniqueRowId>=GUID("1234-1234-111...") 
Patch() - Update or add new, best way to save as it handle collections
Patch() function used to update an existing "Appeal" record.  Also note that a json string is saved- This is how to escape quotes.

Error Handling and Logging:
PowerApps has pretty basic error handling IfError(Try, if fail fall back)
Error Handling for Power Apps
The is a built in mechanism to log from Power Apps into App Insights.

Components:
Build a common UI element such as a menu or header.  The component has input and output parameters so you need to pass in the data to be used and return the output.  This allow the component to be re-used.  Obviously it makes sense that you can't use global variable within components, you need to pass the global variables in using input parameters.
Great example from @Laura-GB https://www.youtube.com/watch?v=5G-gVWRItmc

Sunday 29 September 2019

OAuth for Custom Connectors

Problem:  I have an APIM end point that has both the subscription key and OAuth2 setup for security and I need to connect Power Apps.

There are basically two parts to this problem, setting up your Power App to use OAuth and then also passing in the subscription key on every APIM end point request.
  • This post assumes that both the APIM App registration and the Client App have been registered on Azure AD.
  • Check with postman can access the end point as shown below.  Postman will authenicate and use the bearer token (OAuth) and the subscription as shown below to test
Client ID: 5559555-555a-5558-5554-555d4
Auth URL: https://login.microsoftonline.com/555fd555-555f-5554-5551-555b444c3555/oauth2/v2.0/authorize
Token URL: https://login.microsoftonline.com/555fd555-555f-5554-5551-555b444c3555/oauth2/v2.0/token
Refresh URL: https://login.microsoftonline.com/555fd555-555f-5554-5551-555b444c3555/oauth2/v2.0/authorize


We now know the APIM is working with OAuth and the subscription key.
Configure OAuth from Power Apps:
  • Once Postman can get valid 200 responses using OAuth2 and the subscription key, setup the custom connector.  I could not get the Azure AD connector to work so i used the OAuth connector as shown below: 

Add a policy that will add the subscription key to every https request to the APIM/resources as shown below.

Updated 2 Feb 2020 - Example of custom OAuth code flow authentication for a custom API's using AAD security.

Note: Deploying Custom Connectors in solutions always seems to be an issue.  It is a good idea to keep all connection references in a separate Power Apps Solution.