Difference between API and Webhook from a programmer's perspective - azure

I came across the term Webhook recently (in Azure Alerts, Github deployment, etc.). In my effort to understand the difference between API and Webhook, I read the explanations in stackexchange and sendgrid. My understanding is that the difference is in the way an API is invoked. But this sounds confusing. I think any API does following,
may accept some inputs
perform some action
respond to the caller
If the above mentioned is true, then there is no need for APIs to be categorised based on how they are invoked. At least, this is true from coding perspective as the API is going to work anyway as long as it is invoked and gets the inputs (if required).
Just to explain my understanding of these terms with an example, Azure currently offers (in preview mode as of writing this question) creating Action Groups while setting up Alerts. Two of the alert types supported are Azure Function and Webhook. I could create a Http Trigger Azure function and use it in two Alerts where first one is of Azure Function type and the second one is of the Webhook type. To my surprise, the Webhook type Alert works even though I am using a Http Trigger Azure function (note that, Azure offers template for creating Webhook Azure function too). Below given is the Http Trigger Azure Function I wrote to setup the Webhook for Alert (actual link to code with instructions).
#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public async static Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, ICollector<string> outputQueueItem)
{
log.Info("C# HTTP trigger function processed a request.");
string jsonContent = await req.Content.ReadAsStringAsync();
JToken activityLog = JObject.Parse(jsonContent.ToString())
.SelectToken("data.context.activityLog");
//captures the details of the resource group being modified
log.Info(string.Format("Resource group '{0}' was {1} on {2}.",
(string)activityLog["resourceGroupName"],
((string)activityLog["subStatus"]).ToLower(),
(DateTime)activityLog["eventTimestamp"]));
return req.CreateResponse(HttpStatusCode.OK);
}
At least in the Azure example, it looks like the Webhook Azure function does nothing special, otherwise the Webhook type Alert would not have worked with a Http Trigger Azure function. So, is there any difference in the way of coding or thought process when you code a REST API and Webhook using WebAPI?

Functionally, there is no real difference, but they are different.
With an API, the author defines the spec (audience, protocol, verb, arguments, etc.) for the given endpoint, whereas with a Web Hook, this is specified by a third party.
It is important to maintain the differentiation, as it will help you or other developers to understand how the function is being consumed, and, in the case of a Web Hook, what parts of your solution will be impacted if its intended consumer changes its specification.

After diffing through both Azure HTTP Trigger as well as the "Generic Web hook" functions, I see no difference except that the Web hook mode are offered on both constructs and can be interchangeably used, where the Web hook mode needs a API key whereas its optional on the HTTP Trigger construct.
The Generic JSON option lets you dictate how your Web hook can look like unlike third party providers like Git or Slack.

Related

Can I use a custom hostname for Azure Event grid Topic

I have an Azure Event Grid topic:
https://xxx.westeurope-1.eventgrid.azure.net/api/events
Is there any way to direct clients to publish events to https://xxx.mydomain.com/api/events without getting certificate validation errors, etc.?
It would appear, after researching further documentation and speaking to Microsoft that this is currently not possible. If you create a CNAME entry in your own DNS to point to the Azure fqdn of the endpoint, certificate errors are (understandably) generated.
You could use some type of API gateway to accomplish this. The gateway would have your desired domain name and route for the public to submit requests. A service
behind the gateway would forward the request to the event topic's endpoint.
Another option, but based on the same idea mentioned above, would be to use Azure Functions. The function becomes the gateway and the client publishes to the function's endpoint. Code within the Azure Function bundles the request and forwards it to the event topic.
I'm currently using the Functions approach. My function accepts a generic JSON body, validates a few things, packages it up so it has everything the event topic needs (access keys, headers, correct properties for the event schema, etc), and sends it off to the event topic endpoint. If everything works, I send the client a 200 HTTP status from the Azure Function. If there's a problem, I send a 400 or 500 series status as appropriate.

Right way to implement calling a callback URL in Azure

If I have an API-only app in Azure App Service where users can send a callback URL in the request. The app sends a POST request to the callback URL upon completion.
There are some complexities in implementing calling a callback URL, for example: retries, time between retries, etc.
Is there a service, or set of services, in Azure that can help me implement a callback URL? For example, in AWS the Simple Notification Service (SNS) allows me to send a "push" to a HTTPS endpoint with retries, etc.
Without knowing what sort of context you might need for your callback, you could drop a message in a service bus queue or topic and then write a simple logic app or function which is triggered by the presence of a new message in the queue or topic.
A logic app would provide a solution with no code, only config. A function would require some very basic coding. Logic apps have built in retry features.
Here is an example which somewhat resembles what I think you're after.

azure function webhook key

I am not able to make the azure generic webhook function work with
authlevel keys (function/host/anonymous etc.)
I created a generic webhook function. I understand it is by default protected with function key auth level - is this correct? In such case how to change the authlevel to Host or anonymous?
Next I am calling it from a request-response logic app flow. So I get a request, call the function and then respond back with the result from the function. From the code view of logic app I cannot see any function call that is taking the code and client as parameters. So my question is why is the function call not failing. Is this happening in anonymous mode? Or is there any way the logic app is calling the function with the appropriate parameters (code and clientid) which is not shown even in the code view? Perhaps I am missing some very basic thing - appreciate any help in this regard.
In such case how to change the authlevel to Host or anonymous?
When creating a generic webhook function, you could set the mode for your trigger and the Mode notes as follows:
The mode of the trigger. "Standard" means that the request will be standard HTTP with no additional semantics. "Webhook" means that the request will be processed according to a specified webhook type.
The authLevel property in function.json file does not apply to the WebHook triggers. To trigger a WebHook function the HTTP request must include an API key (e.g. https://<yourapp>.azurewebsites.net/api/<function>?code=<Host key or Function key>). You could choose your generic webhook function, choose your HTTP trigger, then click the Documentation link for more detailed tutorials about HTTP and webhook bindings.
Next I am calling it from a request-response logic app flow. So I get a request, call the function and then respond back with the result from the function.
Based on your scenario, I did the sample flow as follows:
You just need to choose your generic webhook function and logic app would handle the authorization for you. Moreover, the API keys are stored under D:\home\data\Functions\secrets folder, you could use kudu and find them in the host.json or <function-name>.json file. Also, here is a tutorial using PowerShell to access KUDU REST API for retrieving Azure Function key. Additionally, you could add your comment here.

How to make an Approval step in Azure Logic app calling my own APIs similar to office365 approval connector?

I wanna build a small workflow using Azure Logic Apps that contains an "Approval" step, which is simply an API call in my own system, similar to office 365 approval connector.
However, from what I found on the internet, the only way to make a long running task in Azure Logic Apps is to use Webhooks.
In Webhooks, I could not set a value to the parameter I created "Bool-Approved".. so, How can I check it later in a condition step?
The other possible solution maybe is to use Swagger to have an "Bool-Approved" parameter. However, it does not support long running action!
What's the possible solution for me?
As you mentioned, the way to do it is to use the Webhook action, and for that you need to implement the Subscribe/Unsubscribe pattern described here. The webhook action will allow you to get any payload (via an HTTP Post) from the instance-based webhook you are subscribing to.
The points below are a summary of this blog post:
https://www.mexia.com.au/correlation-identifier-pattern-on-logic-apps/
To implement the Subscribe/Unsubscribe Webhook pattern you need to consider:
Subscription store: A database to store the unique message Id and the
instance-based callback URL provided by the webhook action.
Subscribe and Start Request Processing API: this is a RESTful API that is in charge of starting the processing of the request and storing the
subscription.
Unsubscribe and Stop Request Processing API: this is another RESTful API that is only going to be called if the webhook action on the main workflow times out. This API is in charge of stopping the processing and deleting the subscription from the store.
Instance-based webhook: this webhook is to be triggered by your own custom approval event. Once triggered, your webhook is in charge of getting the instance-based callback URL from the store and invoking it. After making the call back to the main workflow instance, the subscription is to be deleted. This is the webhook that is in charge of sending the payload you require to the waiting webhook action in your Logic App.
The subsequent actions will be able to use that response body, so you can implement your conditions, etc.
You can follow the blog post mentioned above to see a detailed example and get more details on how to implement it.
make you api return HTTP code 200 if the response if "ok" and 400 if the response is "not ok". This way you can force logic app to behave the way you need it to behave..

What is a WebHook in Azure

Can anybody explain at a very basic level what a webhook is in azure. Also how do webhooks differ from azure functions and webjobs in azure
There isn't any service available in Azure called "webhook". A webhook is simply an addressable HTTP endpoint that allows external applications to communicate with your system. You could implement webhooks using a variety of Azure services such as Azure Functions, a web app running an API, etc.
This is a bit of a late answer but it may help someone.
In Azure you can use webhooks to trigger an Azure function see Microsoft Functions Documentation
A webhook in azure is an HTTP endpoint. It is a user defined address you can call with relevant information to interact with several other services. Think of it as a sort of mailbox that you can configure services to respond to. You send an HTTP request (mail a letter) and it lands in this mailbox and you have configured say... Azure functions to respond to that particular mailbox or … logic apps or … data factory … The last one for example. You can have data factory post to a webhook when its completed its work if you need some follow on function to be notified upon job complete.
These are different from functions or webjobs in that they do not have any programable logic to execute a task or job. Webhooks are a customizable location to which you can post HTTP requests.
In some main services of Azure like the Container Registry, webhooks are actually listed as a Service within this Service.
Container Registry on the webhook page
With the Container Registry, for example, you can set up a webhook to send out information if there is a new version of a container image available.
The receiving end of the webhook would then be for example the App Service. Here the information can be used to trigger a build of the web app with the updated container image. This example is super easy to setup, because the sending and receiving end are both within Azure. You use the “Continuous Deployment” option within the Container settings of your web app.
Azure Web App page on container settings
When the sending end would be a repository outside of Azure, then the setup is a bit more complicated. If you are interested, check out the learn doc on that:
https://learn.microsoft.com/en-us/learn/modules/deploy-run-container-app-service/6-update-web-app
So in general terms, a webhook is a method to send and receive information from one Service to another. With that you can trigger events or control other functionality. The “web” part means it uses HTTP to transmit the information and the “hook” part means, that you can connect one or more services like that together inside or outside of Azure.
Azure Functions are more or less a highly specialized version of a WebJob built on Azure WebJobs SDK. Webhooks allow you to trigger webjobs and azure functions with an http call.
I'm very late to answer this but in Azure, you can specify a webhook URL to do something when (for example) a shutdown is triggered. You can webhook to email, SMS, alert users, run basic functions, send an APNS to your iOS device, or GCM to an android device.
If you put a URL for your webhook API you effectively send:
A notification will post to the specified webhook endpoint when
the auto-shutdown is about to happen. The endpoint must support
incoming TLS 1.2 connections.
You can also create a Webhook Azure Consumer in Visual Studio. This link has some information stepping you through it: https://www.sparkpost.com/blog/azure-functions/.
Here is a simple code for an Azure Function App (M$ template):
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;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger 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;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
}
API - Always has one answer and interaction (Post, Get...)
A <=====> B
Webhook- is a trigger to run something.
A --------> B
API vs Webhook
Webhook Anatomy in Azure
URL - The address containing a security token used to call the
Runbook.
Request Header - A hash table containing the header information
for the webhook.
Request Body - Data passed to the runbook. The data can be a string,
JSON or XML. The runbook must be able to consume the data type sent
in the webhook.
Webhook Name - The name of the webhook is passed to the runbook.
A Hook by definition is trying to get hold of information from the middle of sequence of flow or process. By the same definition webhook is a type of hook that supports https protocol that infrastructure provider has to support. Azure Webhooks are Https endpoints which can be of two type internal to azure or external to azure. By internal I mean azure function or azure logic apps can be created as a webhook(a https endpoint using trigger connectors), external means you create custom endpoint which which understands the post request send by the azure resource.
Webhook is be used as an alerting or custom processing mechanism to trigger something elsewhere to enable reporting or follow up action.
For example events supported by Microsoft such oncreating ondeleting are all hooks by they are of type native clrhooks

Resources