Connect functions to Azure Storage using Visual Studio Code

Azure Functions lets you connect Azure services and other resources to functions without having to write your own integration code. These bindings, which represent both input and output, are declared within the function definition. Data from bindings is provided to the function as parameters. A trigger is a special type of input binding. Although a function has only one trigger, it can have multiple input and output bindings. To learn more, see Azure Functions triggers and bindings concepts.

This article shows you how to use Visual Studio Code to connect the function you created in the previous quickstart article to Azure Storage. The output binding that you add to this function writes data from the HTTP request to a message in an Azure Queue storage queue.

Most bindings require a stored connection string that Functions uses to access the bound service. To make it easier, you use the Storage account that you created with your function app. The connection to this account is already stored in an app setting named AzureWebJobsStorage.

Prerequisites

Before you start this article, you must meet the following requirements:

This article assumes that you are already signed in to your Azure subscription from Visual Studio Code. You can sign in by running Azure: Sign In from the command palette.

Download the function app settings

In the previous quickstart article, you created a function app in Azure along with the required Storage account. The connection string for this account is stored securely in app settings in Azure. In this article, you write messages to a Storage queue in the same account. To connect to your Storage account when running the function locally, you must download app settings to the local.settings.json file.

  1. Press the F1 key to open the command palette, then search for and run the command Azure Functions: Download Remote Settings.....

  2. Choose the function app you created in the previous article. Select Yes to all to overwrite the existing local settings.

    Important

    Because it contains secrets, the local.settings.json file never gets published, and is excluded from source control.

  3. Copy the value AzureWebJobsStorage, which is the key for the Storage account connection string value. You use this connection to verify that the output binding works as expected.

Register binding extensions

Because you are using a Queue storage output binding, you must have the Storage bindings extension installed before you run the project.

The easiest way to install binding extensions is to enable extension bundles. When you enable bundles, a predefined set of extension packages is automatically installed.

To enable extension bundles, open the host.json file and update its contents to match the following code:

{
    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[1.*, 2.0.0)"
    }
}

Now, you can add the storage output binding to your project.

Add an output binding

In Functions, each type of binding requires a direction, type, and a unique name to be defined in the function.json file. The way you define these attributes depends on the language of your function app.

Binding attributes are defined directly in the function.json file. Depending on the binding type, additional properties may be required. The queue output configuration describes the fields required for an Azure Storage queue binding. The extension makes it easy to add bindings to the function.json file.

To create a binding, right-click (Ctrl+click on macOS) the function.json file in your HttpTrigger folder and choose Add binding.... Follow the prompts to define the following binding properties for the new binding:

Prompt Value Description
Select binding direction out The binding is an output binding.
Select binding with direction... Azure Queue Storage The binding is an Azure Storage queue binding.
The name used to identify this binding in your code msg Name that identifies the binding parameter referenced in your code.
The queue to which the message will be sent outqueue The name of the queue that the binding writes to. When the queueName doesn't exist, the binding creates it on first use.
Select setting from "local.setting.json" AzureWebJobsStorage The name of an application setting that contains the connection string for the Storage account. The AzureWebJobsStorage setting contains the connection string for the Storage account you created with the function app.

A binding is added to the bindings array in your function.json file, which should now look like the following example:

{
   ...

  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Add code that uses the output binding

After the binding is defined, you can use the name of the binding to access it as an attribute in the function signature. By using an output binding, you don't have to use the Azure Storage SDK code for authentication, getting a queue reference, or writing data. The Functions runtime and queue output binding do those tasks for you.

Add code that uses the msg output binding object on context.bindings to create a queue message. Add this code before thecontext.res statement.

// Add a message to the Storage queue.
context.bindings.msg = "Name passed to the function: " + 
(req.query.name || req.body.name);

At this point, your function should look as follows:

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

    if (req.query.name || (req.body && req.body.name)) {
        // Add a message to the Storage queue.
        context.bindings.msg = "Name passed to the function: " + 
        (req.query.name || req.body.name);
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
};

Run the function locally

Azure Functions Core Tools lets you run an Azure Functions project on your local development computer.

  1. To test your function, set a breakpoint in the function code and press F5 to start the function app project. Output from Core Tools is displayed in the Terminal panel.

  2. In the Terminal panel, copy the URL endpoint of your HTTP-triggered function.

    Azure local output

  3. Paste the URL for the HTTP request into your browser's address bar. Append the query string ?name=<yourname> to this URL and execute the request. Execution is paused when the breakpoint is hit.

  4. When you continue the execution, the following shows the response in the browser to the GET request:

    Function localhost response in the browser

  5. To stop debugging, press Shift + F5.

A new queue named outqueue is created in your storage account by the Functions runtime when the output binding is first used. You'll use Storage Explorer to verify that the queue was created along with the new message.

Connect Storage Explorer to your account

Skip this section if you have already installed Azure Storage Explorer and connected it to your Azure account.

  1. Run the Azure Storage Explorer tool, select the connect icon on the left, and select Add an account.

    Add an Azure account to Microsoft Azure Storage Explorer

  2. In the Connect dialog, choose Add an Azure account, choose your Azure environment, and select Sign in....

    Sign in to your Azure account

After you successfully sign in to your account, you see all of the Azure subscriptions associated with your account.

Examine the output queue

  1. In Visual Studio Code, press the F1 key to open the command palette, then search for and run the command Azure Storage: Open in Storage Explorer and choose your Storage account name. Your storage account opens in Azure Storage Explorer.

  2. Expand the Queues node, and then select the queue named outqueue.

    The queue contains the message that the queue output binding created when you ran the HTTP-triggered function. If you invoked the function with the default name value of Azure, the queue message is Name passed to the function: Azure.

    Queue message shown in Azure Storage Explorer

  3. Run the function again, send another request, and you'll see a new message appear in the queue.

Now, it's time to republish the updated function app to Azure.

Redeploy and verify the updated app

  1. In Visual Studio Code, press F1 to open the command palette. In the command palette, search for and select Azure Functions: Deploy to function app....

  2. Choose the function app that you created in the first article. Because you are redeploying your project to the same app, select Deploy to dismiss the warning about overwriting files.

  3. After deployment completes, you can again use cURL or a browser to test the redeployed function. As before, append the query string &name=<yourname> to the URL, as in the following example:

    curl https://myfunctionapp.azurewebsites.net/api/httptrigger?code=cCr8sAxfBiow548FBDLS1....&name=<yourname>
    
  4. Again view the message in the storage queue to verify that the output binding again generates a new message in the queue.

Clean up resources

Resources in Azure refers to function apps, functions, storage accounts, and so forth. They are grouped into resource groups, and you can delete everything in a group by deleting the group.

You created resources to complete these quickstarts. You may be billed for these resources, depending on your account status and service pricing. If you don't need the resources anymore, here's how to delete them:

  1. In Visual Studio Code, press F1 to open the command palette. In the command palette, search for and select Azure Functions: Open in portal.

  2. Choose your function app, and press Enter. The function app page is opened in the Azure portal.

  3. In the Overview tab, select the named link under Resource group.

    Select the resource group to delete from the function app page.

  4. In the Resource group page, review the list of included resources, and verify that they are the ones you want to delete.

  5. Select Delete resource group, and follow the instructions.

    Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

Next steps

You've updated your HTTP triggered function to write data to a Storage queue. To learn more about developing Functions, see Develop Azure Functions using Visual Studio Code.

Next, you should enable Application Insights monitoring for your function app: