Introduction
If you’re a regular visitor here, you may have noticed I cover a lot on the Portal Web API.
It’s a passion of mine for many reasons but especially because it allows us to break free of the standard list and form UI.
Before we ever send an API call, we need to authenticate with the API and prove this is coming from a Power Pages site / Power Apps portal. Don’t worry, this is as simple as copying and pasting a code snippet from Microsoft Docs Microsoft Learn.
We use the same snippet of code every time so I prefer to have this saved in a web template for easy re-use (following Nick Doelman’s excellent advice).
Step 1 – Create a web template containing the function, for easy re-use
Open the Portal Management app
Select Web Templates from the Content section in the left navigation
Click New
Select the required website
Give your web template a name. I use Portal Web API Wrapper
In the Source field, type opening and closing script tags
Copy the wrapper function from https://learn.microsoft.com/en-us/power-pages/configure/write-update-delete-operations#wrapper-ajax-function
Paste the function between your opening and closing script tags
Save your web template
Step 2 – Include (use) your new wrapper function within a web template
Wherever we want to make use of the portal web API, all we need to do to authenticate is to add the link below (before any calls to the API):
{% include 'Portal Web API Wrapper' %}
For convenience, here’s a copy of the web template, ready to copy and re-use:
<script> (function(webapi, $){ function safeAjax(ajaxOptions) { var deferredAjax = $.Deferred(); shell.getTokenDeferred().done(function (token) { // add headers for AJAX if (!ajaxOptions.headers) { $.extend(ajaxOptions, { headers: { "__RequestVerificationToken": token } }); } else { ajaxOptions.headers["__RequestVerificationToken"] = token; } $.ajax(ajaxOptions) .done(function(data, textStatus, jqXHR) { validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve); }).fail(deferredAjax.reject); //AJAX }).fail(function () { deferredAjax.rejectWith(this, arguments); // on token failure pass the token AJAX and args }); return deferredAjax.promise(); } webapi.safeAjax = safeAjax; })(window.webapi = window.webapi || {}, jQuery) </script>