Using Azure Functions with triggers and bindings

Overview

Azure Functions is a serverless computing platform that enables developers to build and run event-driven applications on the cloud. In this tutorial, we will explore how to use Azure Functions with triggers and bindings. Triggers are the events that fire a function and bindings are the connections between the function’s input and output.

By the end of this tutorial, you will learn how to create a simple Azure Function that triggers on an HTTP request and uses bindings to interact with Azure Blob Storage and Azure Table Storage.

Prerequisites

To follow this tutorial, you will need:

  • An Azure account with an active subscription
  • Azure Functions Core Tools installed on your local machine
  • Visual Studio Code or any other code editor

Creating an Azure Functions app

Let’s start by creating an Azure Functions app. Follow these steps:

  1. Log in to your Azure portal.
  2. Click on the Create a resource button in the left-hand pane.
  3. Select Compute > Function App.
  4. Fill in the Function App Name, Subscription, Resource group, OS, and Hosting Plan fields.
  5. Select an appropriate location for the function app.
  6. Click on the Create button.

Wait for a few minutes for Azure to create the function app. Once it’s created, navigate to the function app and click on the Functions tab. You should see a message that says “No functions found. Add a new function.”

Creating an HTTP triggered function

Now, let’s create an HTTP triggered function. Follow these steps:

  1. Click on the Add button to add a new function.
  2. Select HTTP trigger from the options provided.
  3. Fill in the Function name, Route, and Authorization level fields.
  4. Click on the Create button.

Wait for a few seconds for Azure to create the function. Once it’s created, you should see the function’s code in the editor.

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

This is a simple HTTP triggered function that returns a message with a personalized name. You can test this function by clicking on the Test/Run button at the top of the editor.

Once the function is executed, you should see the output and logs in the Output pane at the bottom of the editor.

Using bindings to interact with Azure Blob Storage

Now that we have created an HTTP triggered function, let’s add bindings to it so that we can interact with Azure Blob Storage.

Follow these steps:

  1. Open the function in the editor.
  2. Click on the Integrate tab to open the function’s integration screen.
  3. Click on the New Output button.
  4. Select Azure Blob Storage from the output bindings options.
  5. Fill in the Storage account connection, Path, File name, Block size, Maximum output size, and Content type fields.
  6. Click on the Save button.

Once the binding is created, you can use it in your function’s code. For example, you can modify the HTTP triggered function to save the personalized message to Azure Blob Storage.

const { BlobServiceClient } = require('@azure/storage-blob');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    const account = process.env.AZURE_STORAGE_ACCOUNT;
    const key = process.env.AZURE_STORAGE_ACCESS_KEY;
    const connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;
    const containerName = 'output';
    const blobName = name + '.txt';

    const message = responseMessage;
    const blobServiceClient = account
        ? BlobServiceClient.fromConnectionString(`DefaultEndpointsProtocol=https;AccountName=${account};AccountKey=${key};EndpointSuffix=core.windows.net`)
        : BlobServiceClient.fromConnectionString(connectionString);
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    await blockBlobClient.upload(message, message.length);

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

Notice that we are using the BlobServiceClient class from the @azure/storage-blob package to interact with Azure Blob Storage. We are also using the account, key, and connectionString variables to authenticate with Azure Blob Storage.

You will need to replace the placeholders for the account and key variables with your own storage account’s credentials. Alternatively, you can use the connectionString variable to authenticate with your storage account.

Save the file and test the function. Once the function is successful, navigate to the Azure portal and click on the storage account associated with the function app. You should see a new output container with a file that has the personalized name.

Using bindings to interact with Azure Table Storage

Let’s add another binding that enables us to interact with Azure Table Storage.

Follow these steps:

  1. Open the function in the editor.
  2. Click on the Integrate tab to open the function’s integration screen.
  3. Click on the New Input button.
  4. Select Azure Table Storage from the input bindings options.
  5. Fill in the Table name, Partition key, Row key, and Connection fields.
  6. Click on the Save button.

Once the binding is created, you can use it in your function’s code. For example, you can modify the HTTP triggered function to read and update a row in Azure Table Storage.

const { TableServiceClient, TableClient } = require('@azure/data-tables');

module.exports = async function (context, req, myTableInput) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    const connectionString = process.env.AZURE_TABLES_CONNECTION_STRING;
    const tableName = 'MyTable';
    const partitionKey = 'Partition';
    const rowKey = name;

    const data = myTableInput.data;
    const tableServiceClient = connectionString ? TableServiceClient.fromConnectionString(connectionString) : new TableServiceClient(tableUrl, pipeline);
    const tableClient = tableServiceClient.getTableClient(tableName);
    const entity = Object.assign({ partitionKey, rowKey }, data);
    await tableClient.createEntity(entity);
    context.log('Entity created successfully.');

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

Notice that we are using two classes from the @azure/data-tables package to interact with Azure Table Storage. We are also using the connectionString variable to authenticate with Azure Table Storage.

You will need to replace the placeholder for the connectionString variable with your own storage account’s connection string.

Save the file and test the function. Once the function is successful, navigate to the Azure portal and click on the storage account associated with the function app. You should see a new MyTable table with a row that has the personalized name.

Conclusion

In this tutorial, we explored how to use Azure Functions with triggers and bindings. We created an HTTP triggered function, added bindings to interact with Azure Blob Storage and Azure Table Storage, and modified the function’s code to write and read from these services.

Azure Functions simplify the process of building and deploying event-driven applications on the cloud. With the use of triggers and bindings, developers can use Azure Functions to build powerful applications that interact with Azure services and other APIs.

Related Post