Azure Cosmos DB input binding for Azure Functions 2.x and higher

The Azure Cosmos DB input binding uses the SQL API to retrieve one or more Azure Cosmos DB documents and passes them to the input parameter of the function. The document ID or query parameters can be determined based on the trigger that invokes the function.

For information on setup and configuration details, see the overview.

Note

When the collection is partitioned, lookup operations must also specify the partition key value.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is currently in preview and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. Learn more about the differences between v3 and v4 in the upgrade guide.

Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.

The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.

This article supports both programming models.

Example

Unless otherwise noted, examples in this article target version 3.x of the Azure Cosmos DB extension. For use with extension version 4.x, you need to replace the string collection in property and attribute names with container.

A C# function can be created using one of the following C# modes:

  • In-process class library: compiled C# function that runs in the same process as the Functions runtime.
  • Isolated process class library: compiled C# function that runs in a process isolated from the runtime. Isolated process is required to support C# functions running on .NET 5.0.
  • C# script: used primarily when creating C# functions in the Azure portal.

This section contains examples that require version 3.x of Azure Cosmos DB extension and 5.x of Azure Storage extension. If not already present in your function app, add reference to the following NuGet packages:

The examples refer to a simple ToDoItem type:

        [Function(nameof(DocByIdFromJSON))]
        public void DocByIdFromJSON(
            [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
            [CosmosDBInput(
                databaseName: "ToDoItems",
                containerName: "Items",
                Connection  = "CosmosDBConnection",
                Id = "{ToDoItemId}",
                PartitionKey = "{ToDoItemPartitionKeyValue}")] ToDoItem toDoItem)
        {
            _logger.LogInformation($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId} Key={toDoItemLookup?.ToDoItemPartitionKeyValue}");

            if (toDoItem == null)
            {
                _logger.LogInformation($"ToDo item not found");
            }
            else
            {
                _logger.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
            }
        }

Queue trigger, look up ID from JSON

The following example shows a function that retrieves a single document. The function is triggered by a JSON message in the storage queue. The queue trigger parses the JSON into an object of type ToDoItemLookup, which contains the ID and partition key value to retrieve. That ID and partition key value are used to return a ToDoItem document from the specified database and collection.

        [Function(nameof(DocByIdFromJSON))]
        public void DocByIdFromJSON(
            [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
            [CosmosDBInput(
                databaseName: "ToDoItems",
                containerName: "Items",
                Connection  = "CosmosDBConnection",
                Id = "{ToDoItemId}",
                PartitionKey = "{ToDoItemPartitionKeyValue}")] ToDoItem toDoItem)
        {
            _logger.LogInformation($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId} Key={toDoItemLookup?.ToDoItemPartitionKeyValue}");

            if (toDoItem == null)
            {
                _logger.LogInformation($"ToDo item not found");
            }
            else
            {
                _logger.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
            }
        }

This section contains the following examples:

The examples refer to a simple ToDoItem type:

public class ToDoItem {

  private String id;
  private String description;

  public String getId() {
    return id;
  }

  public String getDescription() {
    return description;
  }

  @Override
  public String toString() {
    return "ToDoItem={id=" + id + ",description=" + description + "}";
  }
}

HTTP trigger, look up ID from query string - String parameter

The following example shows a Java function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a document from the specified database and collection, in String form.

public class DocByIdFromQueryString {

    @FunctionName("DocByIdFromQueryString")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{Query.id}",
              partitionKey = "{Query.partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            Optional<String> item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));

        // Convert and display
        if (!item.isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            // return JSON from Cosmos. Alternatively, we can parse the JSON string
            // and return an enriched JSON object.
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item.get())
                          .build();
        }
    }
}

In the Java functions runtime library, use the @CosmosDBInput annotation on function parameters whose value would come from Azure Cosmos DB. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

HTTP trigger, look up ID from query string - POJO parameter

The following example shows a Java function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. That ID and partition key value used to retrieve a document from the specified database and collection. The document is then converted to an instance of the ToDoItem POJO previously created, and passed as an argument to the function.

public class DocByIdFromQueryStringPojo {

    @FunctionName("DocByIdFromQueryStringPojo")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{Query.id}",
              partitionKey = "{Query.partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Item from the database is " + item);

        // Convert and display
        if (item == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item)
                          .build();
        }
    }
}

HTTP trigger, look up ID from route data

The following example shows a Java function that retrieves a single document. The function is triggered by an HTTP request that uses a route parameter to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a document from the specified database and collection, returning it as an Optional<String>.

public class DocByIdFromRoute {

    @FunctionName("DocByIdFromRoute")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems/{partitionKeyValue}/{id}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{id}",
              partitionKey = "{partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            Optional<String> item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));

        // Convert and display
        if (!item.isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            // return JSON from Cosmos. Alternatively, we can parse the JSON string
            // and return an enriched JSON object.
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item.get())
                          .build();
        }
    }
}

HTTP trigger, look up ID from route data, using SqlQuery

The following example shows a Java function that retrieves a single document. The function is triggered by an HTTP request that uses a route parameter to specify the ID to look up. That ID is used to retrieve a document from the specified database and collection, converting the result set to a ToDoItem[], since many documents may be returned, depending on the query criteria.

Note

If you need to query by just the ID, it is recommended to use a look up, like the previous examples, as it will consume less request units. Point read operations (GET) are more efficient than queries by ID.

public class DocByIdFromRouteSqlQuery {

    @FunctionName("DocByIdFromRouteSqlQuery")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems2/{id}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              sqlQuery = "select * from Items r where r.id = {id}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem[] item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Items from the database are " + item);

        // Convert and display
        if (item == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item)
                          .build();
        }
    }
}

HTTP trigger, get multiple docs from route data, using SqlQuery

The following example shows a Java function that retrieves multiple documents. The function is triggered by an HTTP request that uses a route parameter desc to specify the string to search for in the description field. The search term is used to retrieve a collection of documents from the specified database and collection, converting the result set to a ToDoItem[] and passing it as an argument to the function.

public class DocsFromRouteSqlQuery {

    @FunctionName("DocsFromRouteSqlQuery")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems3/{desc}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              sqlQuery = "select * from Items r where contains(r.description, {desc})",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem[] items,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Number of items from the database is " + (items == null ? 0 : items.length));

        // Convert and display
        if (items == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("No documents found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(items)
                          .build();
        }
    }
}

This section contains the following examples that read a single document by specifying an ID value from various sources:

Queue trigger, look up ID from JSON

The following example shows a TypeScript function that reads a single document and updates the document's text value.

import { app, input, InvocationContext, output } from '@azure/functions';

const cosmosInput = input.cosmosDB({
    databaseName: 'MyDatabase',
    collectionName: 'MyCollection',
    id: '{queueTrigger}',
    partitionKey: '{queueTrigger}',
    connectionStringSetting: 'MyAccount_COSMOSDB',
});

const cosmosOutput = output.cosmosDB({
    databaseName: 'MyDatabase',
    collectionName: 'MyCollection',
    createIfNotExists: false,
    partitionKey: '{queueTrigger}',
    connectionStringSetting: 'MyAccount_COSMOSDB',
});

interface MyDocument {
    text: string;
}

export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise<void> {
    const doc = <MyDocument>context.extraInputs.get(cosmosInput);
    doc.text = 'This was updated!';
    context.extraOutputs.set(cosmosOutput, doc);
}

app.storageQueue('storageQueueTrigger1', {
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [cosmosInput],
    extraOutputs: [cosmosOutput],
    handler: storageQueueTrigger1,
});

HTTP trigger, look up ID from query string

The following example shows a TypeScript function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const cosmosInput = input.cosmosDB({
    databaseName: 'ToDoItems',
    collectionName: 'Items',
    id: '{Query.id}',
    partitionKey: '{Query.partitionKeyValue}',
    connectionStringSetting: 'CosmosDBConnection',
});

interface ToDoDocument {
    description: string;
}

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    const toDoItem = <ToDoDocument>context.extraInputs.get(cosmosInput);
    if (!toDoItem) {
        return {
            status: 404,
            body: 'ToDo item not found',
        };
    } else {
        return {
            body: `Found ToDo item, Description=${toDoItem.description}`,
        };
    }
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [cosmosInput],
    handler: httpTrigger1,
});

HTTP trigger, look up ID from route data

The following example shows a TypeScript function that retrieves a single document. The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const cosmosInput = input.cosmosDB({
    databaseName: 'ToDoItems',
    collectionName: 'Items',
    id: '{id}',
    partitionKey: '{partitionKeyValue}',
    connectionStringSetting: 'CosmosDBConnection',
});

interface ToDoDocument {
    description: string;
}

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    const toDoItem = <ToDoDocument>context.extraInputs.get(cosmosInput);
    if (!toDoItem) {
        return {
            status: 404,
            body: 'ToDo item not found',
        };
    } else {
        return {
            body: `Found ToDo item, Description=${toDoItem.description}`,
        };
    }
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    route: 'todoitems/{partitionKeyValue}/{id}',
    extraInputs: [cosmosInput],
    handler: httpTrigger1,
});

Queue trigger, get multiple docs, using SqlQuery

The following example shows a TypeScript function that retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.

The queue trigger provides a parameter departmentId. A queue message of { "departmentId" : "Finance" } would return all records for the finance department.

import { app, input, InvocationContext } from '@azure/functions';

const cosmosInput = input.cosmosDB({
    databaseName: 'MyDb',
    collectionName: 'MyCollection',
    sqlQuery: 'SELECT * from c where c.departmentId = {departmentId}',
    connectionStringSetting: 'CosmosDBConnection',
});

interface MyDocument {}

export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise<void> {
    const documents = <MyDocument[]>context.extraInputs.get(cosmosInput);
    for (const document of documents) {
        // operate on each document
    }
}

app.storageQueue('storageQueueTrigger1', {
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [cosmosInput],
    handler: storageQueueTrigger1,
});

This section contains the following examples that read a single document by specifying an ID value from various sources:

Queue trigger, look up ID from JSON

The following example shows a JavaScript function that reads a single document and updates the document's text value.

const { app, input, output } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    databaseName: 'MyDatabase',
    collectionName: 'MyCollection',
    id: '{queueTrigger}',
    partitionKey: '{queueTrigger}',
    connectionStringSetting: 'MyAccount_COSMOSDB',
});

const cosmosOutput = output.cosmosDB({
    databaseName: 'MyDatabase',
    collectionName: 'MyCollection',
    createIfNotExists: false,
    partitionKey: '{queueTrigger}',
    connectionStringSetting: 'MyAccount_COSMOSDB',
});

app.storageQueue('storageQueueTrigger1', {
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [cosmosInput],
    extraOutputs: [cosmosOutput],
    handler: (queueItem, context) => {
        const doc = context.extraInputs.get(cosmosInput);
        doc.text = 'This was updated!';
        context.extraOutputs.set(cosmosOutput, doc);
    },
});

HTTP trigger, look up ID from query string

The following example shows a JavaScript function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

const { app, input } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    databaseName: 'ToDoItems',
    collectionName: 'Items',
    id: '{Query.id}',
    partitionKey: '{Query.partitionKeyValue}',
    connectionStringSetting: 'CosmosDBConnection',
});

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [cosmosInput],
    handler: (request, context) => {
        const toDoItem = context.extraInputs.get(cosmosInput);
        if (!toDoItem) {
            return {
                status: 404,
                body: 'ToDo item not found',
            };
        } else {
            return {
                body: `Found ToDo item, Description=${toDoItem.Description}`,
            };
        }
    },
});

HTTP trigger, look up ID from route data

The following example shows a JavaScript function that retrieves a single document. The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

const { app, input } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    databaseName: 'ToDoItems',
    collectionName: 'Items',
    id: '{id}',
    partitionKey: '{partitionKeyValue}',
    connectionStringSetting: 'CosmosDBConnection',
});

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    route: 'todoitems/{partitionKeyValue}/{id}',
    extraInputs: [cosmosInput],
    handler: (request, context) => {
        const toDoItem = context.extraInputs.get(cosmosInput);
        if (!toDoItem) {
            return {
                status: 404,
                body: 'ToDo item not found',
            };
        } else {
            return {
                body: `Found ToDo item, Description=${toDoItem.Description}`,
            };
        }
    },
});

Queue trigger, get multiple docs, using SqlQuery

The following example shows a JavaScript function that retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.

The queue trigger provides a parameter departmentId. A queue message of { "departmentId" : "Finance" } would return all records for the finance department.

const { app, input } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    databaseName: 'MyDb',
    collectionName: 'MyCollection',
    sqlQuery: 'SELECT * from c where c.departmentId = {departmentId}',
    connectionStringSetting: 'CosmosDBConnection',
});

app.storageQueue('storageQueueTrigger1', {
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [cosmosInput],
    handler: (queueItem, context) => {
        const documents = context.extraInputs.get(cosmosInput);
        for (const document of documents) {
            // operate on each document
        }
    },
});

Queue trigger, look up ID from JSON

The following example demonstrates how to read and update a single Azure Cosmos DB document. The document's unique identifier is provided through JSON value in a queue message.

The Azure Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).

{
  "name": "InputDocumentIn",
  "type": "cosmosDB",
  "databaseName": "MyDatabase",
  "collectionName": "MyCollection",
  "id": "{queueTrigger_payload_property}",
  "partitionKey": "{queueTrigger_payload_property}",
  "connectionStringSetting": "CosmosDBConnection",
  "direction": "in"
},
{
  "name": "InputDocumentOut",
  "type": "cosmosDB",
  "databaseName": "MyDatabase",
  "collectionName": "MyCollection",
  "createIfNotExists": false,
  "partitionKey": "{queueTrigger_payload_property}",
  "connectionStringSetting": "CosmosDBConnection",
  "direction": "out"
}

The run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.

param($QueueItem, $InputDocumentIn, $TriggerMetadata)

$Document = $InputDocumentIn 
$Document.text = 'This was updated!'

Push-OutputBinding -Name InputDocumentOut -Value $Document  

HTTP trigger, look up ID from query string

The following example demonstrates how to read and update a single Azure Cosmos DB document from a web API. The document's unique identifier is provided through a querystring parameter from the HTTP request, as defined in the binding's "Id": "{Query.Id}" property.

The Azure Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).

{ 
  "bindings": [ 
    { 
      "type": "cosmosDB", 
      "name": "ToDoItem", 
      "databaseName": "ToDoItems", 
      "collectionName": "Items", 
      "connectionStringSetting": "CosmosDBConnection", 
      "direction": "in", 
      "Id": "{Query.id}", 
      "PartitionKey": "{Query.partitionKeyValue}" 
    },
    { 
      "authLevel": "anonymous", 
      "name": "Request", 
      "type": "httpTrigger", 
      "direction": "in", 
      "methods": [ 
        "get", 
        "post" 
      ] 
    }, 
    { 
      "name": "Response", 
      "type": "http", 
      "direction": "out" 
    },
  ], 
  "disabled": false 
} 

The run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.

using namespace System.Net

param($Request, $ToDoItem, $TriggerMetadata)

Write-Host 'PowerShell HTTP trigger function processed a request'

if (-not $ToDoItem) { 
    Write-Host 'ToDo item not found'

    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
        StatusCode = [HttpStatusCode]::NotFound 
        Body = $ToDoItem.Description 
    })

} else {

    Write-Host "Found ToDo item, Description=$($ToDoItem.Description)"

    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
        StatusCode = [HttpStatusCode]::OK 
        Body = $ToDoItem.Description 
    }) 
}

HTTP trigger, look up ID from route data

The following example demonstrates how to read and update a single Azure Cosmos DB document from a web API. The document's unique identifier is provided through a route parameter. The route parameter is defined in the HTTP request binding's route property and referenced in the Azure Cosmos DB "Id": "{Id}" binding property.

The Azure Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).

{ 
  "bindings": [ 
    { 
      "type": "cosmosDB", 
      "name": "ToDoItem", 
      "databaseName": "ToDoItems", 
      "collectionName": "Items", 
      "connectionStringSetting": "CosmosDBConnection", 
      "direction": "in", 
      "Id": "{id}", 
      "PartitionKey": "{partitionKeyValue}" 
    },
    { 
      "authLevel": "anonymous", 
      "name": "Request", 
      "type": "httpTrigger", 
      "direction": "in", 
      "methods": [ 
        "get", 
        "post" 
      ], 
      "route": "todoitems/{partitionKeyValue}/{id}" 
    }, 
    { 
      "name": "Response", 
      "type": "http", 
      "direction": "out" 
    }
  ], 
  "disabled": false 
} 

The run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.

using namespace System.Net

param($Request, $ToDoItem, $TriggerMetadata)

Write-Host 'PowerShell HTTP trigger function processed a request'

if (-not $ToDoItem) { 
    Write-Host 'ToDo item not found'

    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
        StatusCode = [HttpStatusCode]::NotFound 
        Body = $ToDoItem.Description 
    })

} else { 
    Write-Host "Found ToDo item, Description=$($ToDoItem.Description)"

    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ 
        StatusCode = [HttpStatusCode]::OK 
        Body = $ToDoItem.Description 
    }) 
} 

Queue trigger, get multiple docs, using SqlQuery

The following example demonstrates how to read multiple Azure Cosmos DB documents. The function's configuration file (function.json) defines the binding properties, which includes the sqlQuery. The SQL statement provided to the sqlQuery property selects the set of documents provided to the function.

{ 
  "name": "Documents", 
  "type": "cosmosDB", 
  "direction": "in", 
  "databaseName": "MyDb", 
  "collectionName": "MyCollection", 
  "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}", 
  "connectionStringSetting": "CosmosDBConnection" 
} 

The run1.ps1 file has the PowerShell code which reads the incoming documents.

param($QueueItem, $Documents, $TriggerMetadata)

foreach ($Document in $Documents) { 
    # operate on each document 
} 

This section contains the following examples that read a single document by specifying an ID value from various sources:

The examples depend on whether you use the v1 or v2 Python programming model.

Queue trigger, look up ID from JSON

The following example shows an Azure Cosmos DB input binding. The function reads a single document and updates the document's text value.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.queue_trigger(arg_name="msg", 
                   queue_name="outqueue", 
                   connection="AzureWebJobsStorage")
@app.cosmos_db_input(arg_name="documents", 
                     database_name="MyDatabase",
                     collection_name="MyCollection",
                     id="{msg.payload_property}",
                     partition_key="{msg.payload_property}",
                     connection_string_setting="MyAccount_COSMOSDB")
@app.cosmos_db_output(arg_name="outputDocument", 
                      database_name="MyDatabase",
                      collection_name="MyCollection",
                      connection_string_setting="MyAccount_COSMOSDB")
def test_function(msg: func.QueueMessage,
                  inputDocument: func.DocumentList, 
                  outputDocument: func.Out[func.Document]):
     document = documents[id]
     document["text"] = "This was updated!"
     doc = inputDocument[0]
     doc["text"] = "This was updated!"
     outputDocument.set(doc)
     print(f"Updated document.")

HTTP trigger, look up ID from query string

The following example shows a function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

No equivalent sample for v2 at this time.

HTTP trigger, look up ID from route data

The following example shows a function that retrieves a single document. The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

No equivalent sample for v2 at this time.

Queue trigger, get multiple docs, using SqlQuery

The following example shows an Azure Cosmos DB input binding Python function that uses the binding. The function retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.

The queue trigger provides a parameter departmentId. A queue message of { "departmentId" : "Finance" } would return all records for the finance department.

No equivalent sample for v2 at this time.

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the function. C# script instead uses a function.json configuration file as described in the C# scripting guide.

Attribute property Description
Connection The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being queried. For more information, see Connections.
DatabaseName The name of the Azure Cosmos DB database with the container being monitored.
ContainerName The name of the container being monitored.
PartitionKey Specifies the partition key value for the lookup. May include binding parameters. It is required for lookups in partitioned containers.
Id The ID of the document to retrieve. This property supports binding expressions. Don't set both the Id and SqlQuery properties. If you don't set either one, the entire container is retrieved.
SqlQuery An Azure Cosmos DB SQL query used for retrieving multiple documents. The property supports runtime bindings, as in this example: SELECT * FROM c where c.departmentId = {departmentId}. Don't set both the Id and SqlQuery properties. If you don't set either one, the entire container is retrieved.
PreferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, China North,China North,China North.

Decorators

Applies only to the Python v2 programming model.

For Python v2 functions defined using a decorator, the following properties on the cosmos_db_input:

Property Description
arg_name The variable name used in function code that represents the list of documents with changes.
database_name The name of the Azure Cosmos DB database with the collection being monitored.
collection_name The name of the Azure Cosmos DB collection being monitored.
connection_string_setting The connection string of the Azure Cosmos DB being monitored.
partition_key The partition key of the Azure Cosmos DB being monitored.
id The ID of the document to retrieve.

For Python functions defined by using function.json, see the Configuration section.

Annotations

From the Java functions runtime library, use the @CosmosDBInput annotation on parameters that read from Azure Cosmos DB. The annotation supports the following properties:

Configuration

Applies only to the Python v1 programming model.

The following table explains the properties that you can set on the options object passed to the input.cosmosDB() method. The type, direction, and name properties don't apply to the v4 model.

The following table explains the binding configuration properties that you set in the function.json file, where properties differ by extension version:

function.json property Description
type Must be set to cosmosDB.
direction Must be set to in.
name The variable name used in function code that represents the list of documents with changes.
connection The name of an app setting or setting container that specifies how to connect to the Azure Cosmos DB account being monitored. For more information, see Connections.
databaseName The name of the Azure Cosmos DB database with the container being monitored.
containerName The name of the container being monitored.
partitionKey Specifies the partition key value for the lookup. May include binding parameters. It is required for lookups in partitioned containers.
id The ID of the document to retrieve. This property supports binding expressions. Don't set both the id and sqlQuery properties. If you don't set either one, the entire container is retrieved.
sqlQuery An Azure Cosmos DB SQL query used for retrieving multiple documents. The property supports runtime bindings, as in this example: SELECT * FROM c where c.departmentId = {departmentId}. Don't set both the id and sqlQuery properties. If you don't set either one, the entire container is retrieved.
preferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, China East,China North,China North 2.

See the Example section for complete examples.

Usage

When the function exits successfully, any changes made to the input document are automatically persisted.

The parameter type supported by the Cosmos DB input binding depends on the Functions runtime version, the extension package version, and the C# modality used.

When you want the function to process a single document, the Cosmos DB input binding can bind to the following types:

Type Description
JSON serializable types Functions attempts to deserialize the JSON data of the document into a plain-old CLR object (POCO) type.

When you want the function to process multiple documents from a query, the Cosmos DB input binding can bind to the following types:

Type Description
IEnumerable<T>where T is a JSON serializable type An enumeration of entities returned by the query. Each entry represents one document.
CosmosClient (Preview1)
A client connected to the Cosmos DB account.
Database (Preview1)
A client connected to the Cosmos DB database.
Container (Preview1)
A client connected to the Cosmos DB container.

1 To use these types, you need to reference Microsoft.Azure.Functions.Worker.Extensions.CosmosDB 4.3.1-preview1 or later and the common dependencies for SDK type bindings.

From the Java functions runtime library, the @CosmosDBInput annotation exposes Azure Cosmos DB data to the function. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

Access the document by using context.extraInputs.get().

Updates to documents are not made automatically upon function exit. To update documents in a function use an output binding. See the PowerShell example for more detail.

Data is made available to the function via a DocumentList parameter. Changes made to the document are not automatically persisted.

Connections

The connectionStringSetting/connection and leaseConnectionStringSetting/leaseConnection properties are references to environment configuration which specifies how the app should connect to Azure Cosmos DB. They may specify:

If the configured value is both an exact match for a single setting and a prefix match for other settings, the exact match is used.

Connection string

The connection string for your database account should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

Identity-based connections

If you are using version 4.x or higher of the extension, instead of using a connection string with a secret, you can have the app use an Azure Active Directory identity. To do this, you would define settings under a common prefix which maps to the connection property in the trigger and binding configuration.

In this mode, the extension requires the following properties:

Property Environment variable template Description Example value
Account Endpoint <CONNECTION_NAME_PREFIX>__accountEndpoint The Azure Cosmos DB account endpoint URI. https://<database_account_name>.documents.azure.cn:443/

Additional properties may be set to customize the connection. See Common properties for identity-based connections.

When hosted in the Azure Functions service, identity-based connections use a managed identity. The system-assigned identity is used by default, although a user-assigned identity can be specified with the credential and clientID properties. Note that configuring a user-assigned identity with a resource ID is not supported. When run in other contexts, such as local development, your developer identity is used instead, although this can be customized. See Local development with identity-based connections.

Grant permission to the identity

Whatever identity is being used must have permissions to perform the intended actions. You will need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.

Important

Some permissions might be exposed by the target service that are not necessary for all contexts. Where possible, adhere to the principle of least privilege, granting the identity only required privileges. For example, if the app only needs to be able to read from a data source, use a role that only has permission to read. It would be inappropriate to assign a role that also allows writing to that service, as this would be excessive permission for a read operation. Similarly, you would want to ensure the role assignment is scoped only over the resources that need to be read.

You will need to create a role assignment that provides access to your database account at runtime. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Azure Cosmos DB extension in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles
Trigger Cosmos DB Built-in Data Contributor
Input binding Cosmos DB Built-in Data Reader
Output binding Cosmos DB Built-in Data Contributor

Next steps