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. Select Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

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

    Setting Value Description
    Subscription Your subscription Select the 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 in ID
    Select Create new. Then enter a new resource-group name for your account. For simplicity, use the same name as your ID.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can only contain lowercase letters, numbers, and the hyphen (-) character. It must be between 3 and 31 characters in length.
    API Core(SQL) The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select Core(SQL) because in this article you create a document database and query by using SQL syntax.

    Learn more about the SQL API.
    Location Select the region closest to your users Select a geographic location 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.

    Select Review+Create. You can skip the Network and Tags section.

    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;
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. 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.