Since v1.2.5, Ballerina has had built-in support for Azure Functions. Ballerina recently released the newest version of the Azure Functions package, which uses its service type concepts. This makes it extremely easy for ballerina developers to build and deploy Azure functions.
A crash course on the Azure Functions programming model
Triggers cause a function to run. A trigger defines how a function is invoked and a function must only have one trigger. Triggers have associated data, which are often provided as the payload of the function. In ballerina, triggers are defined using listeners.
Binding to a function is a means of decoratively connecting another resource to the function; bindings can be connected as input bindings, output bindings, or both. In ballerina, data from input bindings are provided to the function as parameters and output bindings are represented by return types.
Let’s get straight into the code to demonstrate the features of the Ballerina. We will be writing a simple application that responds as "Hello World" whenever invoked via HTTP.
Prerequisites
Visual studio code (Optional)
Ballerina Vscode Plugin (Optional)
Azure Functions Vscode Plugin (Optional)
NodeJS (Optional)
Hello World!
First, let's create a ballerina project by executing bal new azf_demo
. Replace the contents of the main.bal
with the following and open the project using vscode.
import ballerinax/azure_functions as af;
service / on new af:HttpListener() {
resource function get greeting() returns json {
return {message: "Hello world"};
}
}
If you are familiar with ballerina, this code should be extremely simple for you. The listener declaration new af:HttpListener()
specifies that the function will be triggered from an HTTP request. As there is no explicit Output binding specified in the return type declaration, it will be HttpOutput
by default. The rest of the code is identical to the ballerina/http
code.
Alright, now let's build the ballerina project by executing bal build
. You should now see commands to deploy the function locally and remotely in the build output.
Let’s run the function locally by executing the func start — script-root target/azure_functions — java
command. If you have the Azure Functions vscode plugin installed, you should be able to see the generated functions in vscode. You can also get the URL of the function by using the plugin or from the command-line output. Additonally, you should be able to use the curl
http://localhost:7071/greeting
command to invoke the locally deployed function.
Once you have locally tested you function, you can deploy it in azure functions. You can use the output given from the bal build
to deploy.
You may use the Azure Functions vs Code plugin to browse the deployed function and to obtain the URL. At this point, you should be able to use the earlier curl command to invoke the locally deployed function.
Dog Review App
Okay, now let's create a slightly more complex application. We are going to create a Dog Review application where users can upload images of their dogs. Here the backend will identify if the picture is a dog, if so generate a description using azure vision, and store the image in the Blob storage and also store the entry on Cosmos DB.
First, let us create the environments required...
Publish — Code
Runtime Stack — Java
Version — 11
Operating System — Windows
In the Review & Create screen, make note of the storage account name.
Go to the created Storage account -> Containers -> New Container
Name — images
Public access level — Blob
Go to Data Explorer -> Create New Container
Create a new database id — reviewdb
Container id — c1
Container throughput — Manual — RU/s — 400 (To stay within the free tier)
- Go to the account created and click on
Keys and Endpoint
, then note down the values ofKey 1
.
First, we will need an HTTP function to receive the client’s request. It’ll perform the required validations and store them in the Blob storage. This will be registered as a function with the HTTP Trigger and Blob Output binding.
import ballerina/http;
import ballerinax/azure_functions as af;
listener af:HttpListener ep = new ();
service /reviews on ep {
resource function post upload(@http:Payload byte[]|error image, string name) returns @af:BlobOutput {path: "images/{Query.name}"} byte[]|error {
return image;
}
}
Next we have another function that listens to the blob storage. This will be invoked when there's a new entry in the blob storage. We will be invoking the Azure Vision API to analyze the image. Finally, we’ll be storing the entry in the Cosmos DB. This will be registered as a function with the Blob Trigger and CosmosDB output binding.
configurable string visionApp = ?;
configurable string subscriptionKey = ?;
configurable string storeAccountName = ?;
public type Entry record {
string id;
boolean isDog;
string imageUrl;
string description;
};
type ImageAnalyzeResponse record {
Category[] categories;
Description description;
string requestId;
Metadata metadata;
string modelVersion;
};
type Description record {
string[] tags;
Caption[] captions;
};
type Caption record {
string text;
decimal confidence;
};
type Category record {
string name;
decimal score;
};
type Metadata record {
int height;
int width;
string format;
};
@af:BlobTrigger {
path: "images/{name}"
}
listener af:BlobListener blobListener = new af:BlobListener();
service "on-image" on blobListener {
remote function onUpdated(byte[] image, @af:BindingName string name) returns @af:CosmosDBOutput {
connectionStringSetting: "CosmosDBConnection",
databaseName: "reviewdb",
collectionName: "c1"
} Entry|error {
var [isDog, description] = check getImageInsights(image);
return {
id: uuid:createType1AsString(),
imageUrl: "https://" + storeAccountName + ".blob.core.windows.net/images/" + name,
isDog: isDog,
description: description
};
}
}
function getImageInsights(byte[] image) returns [boolean, string]|error {
final http:Client clientEndpoint = check new ("https://" + visionApp + ".cognitiveservices.azure.com/vision/v3.2/analyze", {
timeout: 10,
httpVersion: http:HTTP_1_1
});
http:Request req = new ();
req.setBinaryPayload(image);
req.addHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
ImageAnalyzeResponse resp = check clientEndpoint->post("/?visualFeatures=Categories,Description", req);
string[] dogs = from string tag in resp.description.tags
where tag.includes("dog")
select tag;
if (dogs.length() > 0) {
Caption[] captions = resp.description.captions;
string description = "";
if (captions.length() > 0) {
Caption caption = captions[0];
description = caption.text;
}
return [true, description];
}
return [false, ""];
}
We have a separate function that gets executed whenever a HTTP request is sent. It’ll simply query the database and give all the entries within the database. This will be registered as a function along with the HTTP Trigger, CosmosDB Input binding, and HTTP Output binding.
service /dashboard on ep {
resource function get .(@af:CosmosDBInput {
connectionStringSetting: "CosmosDBConnection",
databaseName: "reviewdb",
collectionName: "c1",
sqlQuery: "SELECT * FROM Items"
} Entry[] entries) returns @af:HttpOutput Entry[]|error {
return entries;
}
}
Let’s build the project and deploy it in the Azure functions.
Once the deployment is done, we need to update the application settings to set the values to configurables and the CosmosDB Connection String.
Cosmos DB
Name — CosmosDBConnection
Value — <<Value received from Cosmos DB Keys in step 3>>
If you created the Blob Storage along with the function app, the application setting should already be applied. Therefore, there's no need to configure it again.
You can set environment variables from the Application settings as well. In ballerina, Configurable values need to be passed from the Config.toml
. We can use the BAL_CONFIG_DATA
environment variable to pass Config.toml
contents.
We have three configurable values. You can get the values for these from the values obtained during the environment creation step.
visionApp - Azure Computer Vision App created in step 4 of the environment creation.
subscriptionKey - Subscription key taken from the step 4
Key 1
field.storeAccountName - Name of the storage account created alongside the function app in step 1.
You can find a sample application config entry below. You need to replace the existing values with the actual values from the environment you've created as explained above.
Name -
BAL_CONFIG_DATA
Value -
visionApp= "bal-review-vision1" \n subscriptionKey = "9abdcbxxxx" \n storeAccountName = "balreviewappstore"
Now the functions are all ready. You can invoke these functions manually, but to simplify the process, I’ve created a web app that makes use of these functions we just deployed. This web app is built using the React and tailwind CSS. This web app simply calls the dashboard function to retrieve entries from the database and displays each entry. In addition, it also calls the upload function whenever an image is uploaded by the user. I will not go into detail about the web app implementation, but you can find the complete code on GitHub. You need to replace the value of the functionApp
variable in App.js
with the function app you created in the prerequisites. Finally, you need to go to the function app in the azure portal and add cors settings, so that your front end can communicate properly.
Next, you can simply start the function by executing npm start
. Now you should be able to upload photos and view the photos and descriptions generated by the azure platform for the uploaded photos.
You can find the code for this blog in this repository. Feel free to modify and play around with the Ballerina azure functions. More information on Azure Functions in Ballerina can be found via the following resources:
https://github.com/ballerina-platform/module-ballerinax-azure.functions/blob/master/spec/spec.md
https://github.com/ballerina-platform/module-ballerinax-azure.functions
https://ballerina.io/learn/by-example/azure-functions-deployment.html
If this is your first time writing code using ballerina, I highly recommend you try out the ballerina language. It is a very powerful programming language built to write network applications. Happy Coding!