An Azure Function Microservice Cookbook

“You have to do it and do it, until you get it right.”

Julia Child

In hockey they call it a hat trick. In horse racing it’s the triple crown. In programming we just call it slogging through until you get it right.

That’s pretty much how I feel now that I have figured out how to write microservices for the big three cloud computing platforms — Amazon Web Services (AWS), Google, and Azure. I’ve already written about my adventures with Lambda and Google Cloud Functions. I am completing the trilogy today with Azure Functions.

At the end of my research, I learned that there isn’t a whole lot of difference between the resultant microservice on any of the platforms. Source code, invocation, and configuration are all pretty similar. In fact, the differences between Google and AWS are pretty minor and if you know one, you pretty much know the other.

That isn’t as true with Azure. While the final product is practically the same as the others, getting there is a horse of a different color. I am able to use my normal programming routines to write AWS and Google functions, but Azure requires me to use Microsoft Visual Studio for nearly all the heavy lifting. That’s not to say that Visual Studio is a bad IDE (Integrated Development Environment), it’s just not what I am used to and I was a little peeved that I had to download and learn something new just to write a REST service.

By the way, I can’t afford the full Visual Studio IDE so I used the free Visual Studio Code IDE. With the exception of not being able to create a project, it worked well enough.

In addition to using Visual Studio to write my code, it became the tool to package it up and deploy it to the Azure cloud. This was accomplished by loading a bunch of extensions into VS and connecting the IDE into my Azure account. So, while some might call this simplifying the process (I can do most of everything in one place), it felt like Microsoft taking too much control over my programming workflow. I am a creature of habit and don’t like folks messing with my routines.

That said, I was able to build my microservice and invoke it as a public URL without too much whining.

Coinbase and Bitcoin Prices Once Again

Those of you who read my Lambda and Google articles should be familiar with my Coinbase integration. For consistency, I wrote the same function in Azure. I also integrated it into an Avaya Virtual Agent. Rather that repeating all those steps, I will assume you know what I am attempting to accomplish with Azure. Please go back to those articles if you have any questions. They thoroughly explain the process.

I also don’t want to walk you through all the steps required to create an Azure Function. Trust me, that would require a lot of screen grabs and text. Instead, I will refer you to this Microsoft article. Although I didn’t stumble upon it until after I had mucked my way through the process with bits and pieces of other articles and brute force trial and error, it looks pretty comprehensive.

Note: This is also a pretty good video. It’s long and covers material beyond the scope of this article, but you can always skip around after you’ve read the above Microsoft article.

There is one thing that the article lacks and that is how to add dependencies. In my Coinbase code, I use the request-promise library. To install the library to my development folder, I opened up a Terminal window from Visual Studio (Terminal –> New Terminal) and ran “npm install request-promise.” You need to do that for any libraries your function code references.

The Azure version of the Coinbase code looks a lot like what I wrote for Google and the Google code is very similar to its Lambda sister. For Azure, the entry point is:

module.exports = async function (context, req)

Data is returned to the caller using:

context.res

// An Azure Function to retrieve the current Bitcoin value in four different currencies

const request = require('request-promise');
const COINBASE_URL = "https://api.coinbase.com/v2/prices/spot?currency=";

module.exports = async function (context, req) {
	var body;
	var virtualAgentResult = {
		amount: null
	}
	
	var currency;
	if (req.body.UserInput.value == "1") {
		currency = "USD";
	} else if (req.body.UserInput.value == "2") {
		currency = "GBP";
	} else if (req.body.UserInput.value == "3") {
		currency = "CAD";
	} else if (req.body.UserInput.value == "4") {
		currency = "MXN";
	}
		
	var url = COINBASE_URL + currency;
	var options = {
		'method': 'GET',
		'url': url,
		'headers': {
			'Accept': 'application/json'
		}
	};
	try {
		var coinbaseResponse = await request.get(options, function(e , r , body) {
		});	
		var jsonResponse = JSON.parse(coinbaseResponse);
				
		// Massage amount information for the Virtual Agent prompt
		var amount = jsonResponse.data.amount.split(".");
		var newAmount;
		if (req.body.UserInput.value == "4") {
			newAmount = amount[0] + " pesos and " + amount[1].substring(0, 2) + " centavos";
		} else if (req.body.UserInput.value == "2") {
			newAmount = amount[0] + " pound sterling and " + amount[1].substring(0, 2) + " pence";
		} else {				
			newAmount = amount[0] + " dollars and " + amount[1].substring(0, 2) + " cents";
		}
		virtualAgentResult.amount = newAmount;
		context.res = {
			status: 200, 
			body: JSON.stringify(virtualAgentResult)
		};
	} catch (e) {
		context.res = {
			status: 200, 
			body: JSON.stringify(virtualAgentResult)
		};
	}		
};

Once you are happy with the code, Visual Studio can deploy it to the Azure cloud.

I always test my REST functions using Google Postman. I found the public URL by going to the Azure webpage for my Resource and Function. Check out the “Get function URL” link. I expect you can find the URL in Visual Studio, too, but I wasn’t able to crack that nut.

Invoking the function in Postman gives me the expected results.:

Mischief Managed

With that, my hat trick is complete. As I wrote in my previous two articles, I am completely sold on microservices for this kind of programming. I love not having to create an Express application and worrying about certificates, redundancy, failover, etc. for my REST calls. All three of these platforms make this possible. Some are a little more complicated than others (take a hint, Microsoft), but nothing is too hard. Heck, if a guy like me can do it, so can you.

Happy Programming!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: