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.

Cosmos DB

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. In a new browser window, sign in to the Azure portal.
  2. Click Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In the New account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    ID Enter a unique name Enter a unique name to identify this Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique but identifiable ID.

    The ID can contain only lowercase letters, numbers, and the hyphen (-) character, and it must contain 3 to 50 characters.
    API SQL The API determines the type of account to create. Azure Cosmos DB provides five APIs: SQL (document database), Gremlin (graph database), MongoDB (document database), Azure Table, and Cassandra. Each API currently requires you to create a separate account.

    Select SQL because in this quickstart you are creating a document database that is queryable using SQL syntax and accessible with the SQL API.

    Learn more about the SQL API
    Subscription Your subscription Select Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided above in ID
    Select Create New, then enter a new resource-group name for your account. For simplicity, you can use the same name as your ID.
    Location Select the region closest to your users Select geographic location in which to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
    Enable geo-redundancy Leave blank This creates a replicated version of your database in a second (paired) region. Leave this blank.
    Pin to dashboard Select Select this box so that your new database account is added to your portal dashboard for easy access.

    Then click Create.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. Wait for the portal to display the Congratulations! Your Azure Cosmos DB account was created page.

    The Azure portal Notifications pane

Add an output binding

  1. In the portal, navigate to the function app you created previously and expand both your function app and your function.

  2. Select Integrate and + New Output, which is at the top right of the page. Choose Azure Cosmos DB, and click Select.

    Add an Azure Cosmos DB output binding

  3. If you get an Extensions not installed message, choose Install to install the Azure Cosmos DB bindings extension in the function app. Installation may take a minute or two.

    Install the Azure Cosmos DB binding extension

  4. Use the Azure Cosmos DB output settings as specified in the table:

    Configure Cosmos DB output binding

    Setting Suggested value Description
    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 Checked The collection doesn't already exist, so create it.
    Azure Cosmos DB account connection New setting Select New, then choose your Subscription, the Database account you created earlier, and Select. Creates an application setting for your account connection. This setting is used by the binding to connection to the database.
    Collection throughput 400 RU If you want to reduce latency, you can scale up the throughput later.
  5. Select Save 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;

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. Expand the right window and select Test. Under Query, click + Add parameter and add the following parameters to the query string:

    • name
    • task
    • duedate
  2. Click Run and verify that a 200 status is returned.

    Configure Cosmos DB output binding

  3. On the left side of the Azure portal, expand the icon bar, type cosmos in the search field, and select Azure Cosmos DB.

    Search for the Cosmos DB service

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

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

    Verify Cosmos DB entry

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 left menu in the Azure portal, select Resource groups and then select myResourceGroup.

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

Select Delete, type myResourceGroup in the text box, and then select Delete.

Next steps

Learn how to create functions with other kinds of triggers or how to integrate functions with other Azure services.

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