Azure Functions & Cosmos DB Input Binding

Overview

This document explains how to use the Azure Cosmos DB input binding in Azure Functions. This binding allows your function to retrieve documents from a Cosmos DB container efficiently and declaratively.

The input binding simplifies data retrieval by mapping query results directly to function parameters, eliminating the need for explicit SDK calls within your function code for simple read operations.

Configuration

To configure the Cosmos DB input binding, you define it in your function.json file. Here's a typical configuration:


{
  "scriptFile": "run.cs",
  "bindings": [
    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "ToDoList",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "id": "{id}",
      "partitionKey": "{partitionKey}"
    },
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get"
      ],
      "authLevel": "function"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ]
}
            

Key Properties:

You can also specify a sqlQuery property instead of id and partitionKey to execute a more complex query.

Usage in Function Code

The data retrieved by the input binding is automatically passed as an argument to your function. The type of the argument depends on the expected return type of the query.

Example: C#

If your function.json specifies a single document retrieval, you can bind it to a POCO (Plain Old CLR Object) or a dynamic object.


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

public static class GetCosmosDbItem
{
    [FunctionName("GetCosmosDbItem")]
    public static async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "items/{id}")] HttpRequest req,
        string id,
        [CosmosDB(
            databaseName: "ToDoList",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            Id = "{id}",
            PartitionKey = "{id}" // Assuming ID is also the partition key for simplicity
        )] Item item, // Or dynamic, or a List if using SQL Query
        ILogger log)
    {
        log.LogInformation($"C# HTTP trigger function processed a request to get item with ID: {id}");

        if (item == null)
        {
            log.LogWarning($"Item with ID '{id}' not found.");
            return new NotFoundResult();
        }

        log.LogInformation($"Item found: {item.Description}");
        return new OkObjectResult(item);
    }
}

// Define your Item POCO
public class Item
{
    public string Id { get; set; }
    public string Description { get; set; }
    public bool IsComplete { get; set; }
    // Add other properties as needed
}
            

Example: JavaScript

In JavaScript, you can bind to an object or an array of objects.


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

    if (!context.bindings.inputDocument) {
        context.log('Document not found.');
        context.res = { status: 404, body: "Document not found" };
        return;
    }

    context.log('Document found:', context.bindings.inputDocument);
    context.res = {
        status: 200,
        body: context.bindings.inputDocument
    };
};
            

In the JavaScript example, context.bindings.inputDocument would contain the document retrieved by the Cosmos DB input binding defined in function.json.

Common Scenarios & Best Practices