Wednesday, May 6, 2020

Quick Intro to Azure Functions

I've been working on a small web application for my wife to help her evaluate her preschool students. I created this application as a single page application (SPA) and backing APIs. For the SPA, I used VueJS. For the backing API, I used Azure Functions.

Azure Functions are Microsoft's serverless computing offering. They allow a developer to create functionality based on several triggers. Triggers can be HTTP, queues, Azure Storage, and so on. One of the most commonly used triggers is HTTP. A function based on an HTTP trigger fires for a web request. I think about this like a Model View Controller (MVC) application with the models and controllers and none of the boilerplate code that goes with a full API application.

An Azure Function application consists of a minimum set of files. Those files are:

host.json
local.settings.json
FunctionApp.csproj
Function.cs
Where "FunctionApp" and "Function" are the names you give your Azure Function.

The host.json file contains runtime information, including the version of Azure Functions being used and things like logging configurations. The local.settings.json file contains application-specific settings including connection strings. The CSPROJ file is a fairly typical C# project file that specifies any package dependencies and things like that. The CS file is the "function" itself. It looks like a typcial static C# class except for an annotation and a specific method signature.

The "function" that serves as a trigger for your function app is annotated with [FunctionName("MyFunction")]. This annotation specifies the publicly visible name that your function will have. The function signature is specific to the type of trigger for your function. Since I used an HTTP trigger, my function signature looked like:

public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
This signature tells the runtime that I am using an HTTP trigger that responds to HTTP GET and POST requests. I don't specify a specific route. The HttpRequest and a default logger are supplied using the dependency injection that is baked into the service.

When you generate your first function, a default "Hello World" app is created. This application illustrates how to work with the HttpRequest object passed into the function. It also shows how to create the IActionResult to pass output from the function.

For my specific Azure Function app, I put just enough code into the function itself to handle the request and return a response. I created service and repository classes for handling the business logic and data movement for the calls. This approach worked very well for me!

This approach to API development allowed me to get something created and deployed very quickly. I was able to utilize some basic tooling from Microsoft to build, test, and deploy my API very quickly.

No comments:

Post a Comment