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:
- name: The name of the parameter in your function code that will hold the retrieved document(s).
- type: Must be cosmosDB for this binding.
- direction: Set to in for an input binding.
- databaseName: The name of your Cosmos DB database.
- collectionName: The name of the container to query.
- connectionStringSetting: The name of the application setting that stores your Cosmos DB connection string.
- id: The ID of the document to retrieve. Typically uses a binding expression like "{id}" to get the ID from an incoming request or another trigger.
- partitionKey: (Optional) The partition key value for the document. Also uses binding expressions like "{partitionKey}". If your container uses a synthetic partition key, you might need to construct it here.
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
- Retrieving a single document: Use id and partitionKey.
- Retrieving multiple documents: Use the sqlQuery property in function.jsonand bind the parameter to a collection type (e.g., IEnumerable<T> in C#, or an array in JavaScript).
- Partition Key Handling: Ensure you correctly specify the partitionKey or construct it using binding expressions if necessary. Incorrect partition key handling can lead to performance issues or errors.
- Error Handling: Always check if the retrieved data is null or empty, especially when retrieving single documents.
- Connection Strings: Store your Cosmos DB connection string securely in application settings, not directly in function.json.
- Performance: For complex queries or large result sets, consider if the input binding is the most efficient approach compared to using the Cosmos DB SDK directly.