Today’s post will be on how to expose an API hosted via an Azure function via Azure API management. So what are we going to configure today? We’ll expose the function API externally. The “user” (or client app) will authenticate with API management via a “subscription key“. Afterwards API management will call the back-end function, where it will authenticate via the function authentication code.
So let’s go to our function …
Where we’ll grab the “function URL”. This contains the query parameter “code” which uses the function key as authentication.
Now let’s go the “Platform features” and then “API definition”.
Here I’ve already configured my swagger definition to ease up the exposing of my function. Let’s copy the API definition URL which we can use to import the function into API management.
Once that’s all imported and so on… Let’s go to the “policies” in the publisher portal of API management. Select the specific API, and we’ll add the “set-query-string-parameter” . Here we’ll set the query parameter name to “code”, and as value, we’ll add the function code to ensure the authentication part being inserted upon a request to the back-end.
So far, so good… Now let’s test the API. Browse to “APIs” in the portal, and then to the published API…
If you would take a quick glance towards “all operations”, then you can see that the query parameter “code” will be inserted during the inbound processing.
Now let’s do a quick test… Browse to “Test” and press “Send”.
And we’ll see that we’re receiving results from our back-end API! Nice nice… So everything is working.
Now let’s take a look at what happened. Go to “Trace” and then to “Backend” ;
Here we’ll see that the request url has been enriched with the query parameter code and the authorization code.
So now we’re sure the API management is able to call our back-end API. Next we’ll test if our client is able to call the API management and get the results via the subscription key.
From the developer portal, copy the subscription key. And use that one to call the API ;
And that also gives the expected results! Cool!!!
Why do you want to put API Management in front of functions?
- Abstraction of the back-end APIs. This enables you to have more user friendly URIs, but more importantly, it will also provide you with the ability to switch back-end APIs without your users knowing it.
- Once you built an API, you can publish it internally/externally and let people re-use it. This has advantages that the wheel does not need to re-invented once again.
- In addition, you can also have several subscription plans without having to code this complexity into each individual API.
- Caching! Functions are billed per 100 milliseconds they run. If you have an insanely popular API, then caching will reduce the costs of the back-end API. Or for non-serverless workloads, you could reduce the needed capacity of the services powering your API in general.