Store unstructured data using Azure Functions and Azure Cosmos DB

Azure Cosmos DB is a great way to store unstructured and JSON data. Combined with Azure Functions, Cosmos DB makes storing data quick and easy with much less code than required for storing data in a relational database.

Note

At this time, the Azure Cosmos DB trigger, input bindings, and output bindings work with SQL API and Graph API accounts only.

In Azure Functions, input and output bindings provide a declarative way to connect to external service data from your function. In this article, learn how to update an existing function to add an output binding that stores unstructured data in an Azure Cosmos DB document.

Prerequisites

To complete this tutorial:

This topic uses as its starting point the resources created in Create your first function from the Azure portal. If you haven't already done so, please complete these steps now to create your function app.

Create an Azure Cosmos DB account

You must have an Azure Cosmos DB account that uses the SQL API before you create the output binding.

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. On the New page, search for and select Azure Cosmos DB.

  3. On the Azure Cosmos DB page, select Create.

  4. On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name A unique name Enter a name to identify your Azure Cosmos account. Because documents.azure.com is appended to the name that you provide to create your URI, use a unique name.

    The name can only contain lowercase letters, numbers, and the hyphen (-) character. It must be between 3-44 characters in length.
    API The type of account to create Select Core (SQL) to create a document database and query by using SQL syntax.

    The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. Currently, you must create a separate account for each API.
    Apply Free Tier Discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. Learn more about free tier.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Account Type Production or Non-Production Select Production if the account will be used for a production workload. Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. You can change this value anytime.

    Note

    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    The new account page for Azure Cosmos DB

  5. Select Review + create. You can skip the Network and Tags sections.

  6. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  7. Select Go to resource to go to the Azure Cosmos DB account page.

    The Azure Cosmos DB account page

Add an output binding

  1. In the Azure portal, navigate to and select the function app you created previously.

  2. Select Functions, and then select the HttpTrigger function.

    Select your Http function in the Azure portal.

  3. Select Integration and + Add output.

    Add an Azure Cosmos DB output binding.

  4. Use the Create Output settings as specified in the table:

    Configure Azure Cosmos DB output binding.

    Setting Suggested value Description
    Binding Type Azure Cosmos DB Name of the binding type to select to create the output binding to Azure Cosmos DB.
    Document parameter name taskDocument Name that refers to the Cosmos DB object in code.
    Database name taskDatabase Name of database to save documents.
    Collection name taskCollection Name of the database collection.
    If true, creates the Cosmos DB database and collection Yes The collection doesn't already exist, so create it.
    Cosmos DB account connection New setting Select New, then choose Azure Cosmos DB Account and the Database account you created earlier, and then select OK. Creates an application setting for your account connection. This setting is used by the binding to connection to the database.
  5. Select OK to create the binding.

Update the function code

Replace the existing function code with the following code, in your chosen language:

Replace the existing C# function with the following code:

#r "Newtonsoft.Json"

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

public static IActionResult Run(HttpRequest req, out object taskDocument, ILogger log)
{
    string name = req.Query["name"];
    string task = req.Query["task"];
    string duedate = req.Query["duedate"];

    // We need both name and task parameters.
    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(task))
    {
        taskDocument = new
        {
            name,
            duedate,
            task
        };

        return (ActionResult)new OkResult();
    }
    else
    {
        taskDocument = null;
        return (ActionResult)new BadRequestResult();
    }
}

This code sample reads the HTTP Request query strings and assigns them to fields in the taskDocument object. The taskDocument binding sends the object data from this binding parameter to be stored in the bound document database. The database is created the first time the function runs.

Test the function and database

  1. Select Test. Under Query, select + Add parameter and add the following parameters to the query string:

    • name
    • task
    • duedate

    Test the function.

  2. Select Run and verify that a 200 status is returned.

    Test the function.

  3. In the Azure portal, search for and select Azure Cosmos DB.

    Search for the Cosmos DB service.

  4. Choose your Azure Cosmos DB account, then select Data Explorer.

  5. Expand the TaskCollection nodes, select the new document, and confirm that the document contains your query string values, along with some additional metadata.

    Verify the string values in your document.

You've successfully added a binding to your HTTP trigger to store unstructured data in an Azure Cosmos DB.

Clean up resources

In the preceding steps, you created Azure resources in a resource group. If you don't expect to need these resources in the future, you can delete them by deleting the resource group.

From the Azure portal menu or Home page, select Resource groups, and on the Resource groups page, select myResourceGroup.

On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.

Select Delete resource group, type myResourceGroup in the text box to confirm, and then select Delete.

Next steps

For more information about binding to a Cosmos DB database, see Azure Functions Cosmos DB bindings.