Rediger

Del via


Azure Tables output bindings for Azure Functions

Use an Azure Tables output binding to write entities to a table in Azure Cosmos DB for Table or Azure Table Storage.

For information on setup and configuration details, see the overview

Note

This output binding only supports creating new entities in a table. If you need to update an existing entity from your function code, instead use an Azure Tables SDK directly.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.

Example

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

  • Isolated worker model: Compiled C# function that runs in a worker process that's isolated from the runtime. Isolated worker process is required to support C# functions running on LTS and non-LTS versions .NET and the .NET Framework. Extensions for isolated worker process functions use Microsoft.Azure.Functions.Worker.Extensions.* namespaces.
  • In-process model: Compiled C# function that runs in the same process as the Functions runtime. In a variation of this model, Functions can be run using C# scripting, which is supported primarily for C# portal editing. Extensions for in-process functions use Microsoft.Azure.WebJobs.Extensions.* namespaces.

The following MyTableData class represents a row of data in the table:

public class MyTableData : Azure.Data.Tables.ITableEntity
{
    public string Text { get; set; }

    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
}

The following function, which is started by a Queue Storage trigger, writes a new MyDataTable entity to a table named OutputTable.

[Function("TableFunction")]
[TableOutput("OutputTable", Connection = "AzureWebJobsStorage")]
public static MyTableData Run(
    [QueueTrigger("table-items")] string input,
    [TableInput("MyTable", "<PartitionKey>", "{queueTrigger}")] MyTableData tableInput,
    FunctionContext context)
{
    var logger = context.GetLogger("TableFunction");

    logger.LogInformation($"PK={tableInput.PartitionKey}, RK={tableInput.RowKey}, Text={tableInput.Text}");

    return new MyTableData()
    {
        PartitionKey = "queue",
        RowKey = Guid.NewGuid().ToString(),
        Text = $"Output record with rowkey {input} created at {DateTime.Now}"
    };
}

The following example shows a Java function that uses an HTTP trigger to write a single table row.

public class Person {
    private String PartitionKey;
    private String RowKey;
    private String Name;

    public String getPartitionKey() {return this.PartitionKey;}
    public void setPartitionKey(String key) {this.PartitionKey = key; }
    public String getRowKey() {return this.RowKey;}
    public void setRowKey(String key) {this.RowKey = key; }
    public String getName() {return this.Name;}
    public void setName(String name) {this.Name = name; }
}

public class AddPerson {

    @FunctionName("addPerson")
    public HttpResponseMessage get(
            @HttpTrigger(name = "postPerson", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION, route="persons/{partitionKey}/{rowKey}") HttpRequestMessage<Optional<Person>> request,
            @BindingName("partitionKey") String partitionKey,
            @BindingName("rowKey") String rowKey,
            @TableOutput(name="person", partitionKey="{partitionKey}", rowKey = "{rowKey}", tableName="%MyTableName%", connection="MyConnectionString") OutputBinding<Person> person,
            final ExecutionContext context) {

        Person outPerson = new Person();
        outPerson.setPartitionKey(partitionKey);
        outPerson.setRowKey(rowKey);
        outPerson.setName(request.getBody().get().getName());

        person.setValue(outPerson);

        return request.createResponseBuilder(HttpStatus.OK)
                        .header("Content-Type", "application/json")
                        .body(outPerson)
                        .build();
    }
}

The following example shows a Java function that uses an HTTP trigger to write multiple table rows.

public class Person {
    private String PartitionKey;
    private String RowKey;
    private String Name;

    public String getPartitionKey() {return this.PartitionKey;}
    public void setPartitionKey(String key) {this.PartitionKey = key; }
    public String getRowKey() {return this.RowKey;}
    public void setRowKey(String key) {this.RowKey = key; }
    public String getName() {return this.Name;}
    public void setName(String name) {this.Name = name; }
}

public class AddPersons {

    @FunctionName("addPersons")
    public HttpResponseMessage get(
            @HttpTrigger(name = "postPersons", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION, route="persons/") HttpRequestMessage<Optional<Person[]>> request,
            @TableOutput(name="person", tableName="%MyTableName%", connection="MyConnectionString") OutputBinding<Person[]> persons,
            final ExecutionContext context) {

        persons.setValue(request.getBody().get());

        return request.createResponseBuilder(HttpStatus.OK)
                        .header("Content-Type", "application/json")
                        .body(request.getBody().get())
                        .build();
    }
}

The following example shows a table output binding that writes multiple table entities.

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

const tableOutput = output.table({
    tableName: 'Person',
    connection: 'MyStorageConnectionAppSetting',
});

interface PersonEntity {
    PartitionKey: string;
    RowKey: string;
    Name: string;
}

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    const rows: PersonEntity[] = [];
    for (let i = 1; i < 10; i++) {
        rows.push({
            PartitionKey: 'Test',
            RowKey: i.toString(),
            Name: `Name ${i}`,
        });
    }
    context.extraOutputs.set(tableOutput, rows);
    return { status: 201 };
}

app.http('httpTrigger1', {
    methods: ['POST'],
    authLevel: 'anonymous',
    extraOutputs: [tableOutput],
    handler: httpTrigger1,
});
const { app, output } = require('@azure/functions');

const tableOutput = output.table({
    tableName: 'Person',
    connection: 'MyStorageConnectionAppSetting',
});

app.http('httpTrigger1', {
    methods: ['POST'],
    authLevel: 'anonymous',
    extraOutputs: [tableOutput],
    handler: async (request, context) => {
        const rows = [];
        for (let i = 1; i < 10; i++) {
            rows.push({
                PartitionKey: 'Test',
                RowKey: i.toString(),
                Name: `Name ${i}`,
            });
        }
        context.extraOutputs.set(tableOutput, rows);
        return { status: 201 };
    },
});

The following example demonstrates how to write multiple entities to a table from a function.

Binding configuration in function.json:

{
  "bindings": [
    {
      "name": "InputData",
      "type": "manualTrigger",
      "direction": "in"
    },
    {
      "tableName": "Person",
      "connection": "MyStorageConnectionAppSetting",
      "name": "TableBinding",
      "type": "table",
      "direction": "out"
    }
  ],
  "disabled": false
}

PowerShell code in run.ps1:

param($InputData, $TriggerMetadata)

foreach ($i in 1..10) {
    Push-OutputBinding -Name TableBinding -Value @{
        PartitionKey = 'Test'
        RowKey = "$i"
        Name = "Name $i"
    }
}

The following example demonstrates how to use the Table storage output binding. Configure the table binding in the function.json by assigning values to name, tableName, partitionKey, and connection:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "message",
      "type": "table",
      "tableName": "messages",
      "partitionKey": "message",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    },
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

The following function generates a unique UUI for the rowKey value and persists the message into Table storage.

import logging
import uuid
import json

import azure.functions as func

def main(req: func.HttpRequest, message: func.Out[str]) -> func.HttpResponse:

    rowKey = str(uuid.uuid4())

    data = {
        "Name": "Output binding message",
        "PartitionKey": "message",
        "RowKey": rowKey
    }

    message.set(json.dumps(data))

    return func.HttpResponse(f"Message created with the rowKey: {rowKey}")

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.

In C# class libraries, the TableInputAttribute supports the following properties:

Attribute property Description
TableName The name of the table to which to write.
PartitionKey The partition key of the table entity to write.
RowKey The row key of the table entity to write.
Connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Annotations

In the Java functions runtime library, use the TableOutput annotation on parameters to write values into your tables. The attribute supports the following elements:

Element Description
name The variable name used in function code that represents the table or entity.
dataType Defines how Functions runtime should treat the parameter value. To learn more, see dataType.
tableName The name of the table to which to write.
partitionKey The partition key of the table entity to write.
rowKey The row key of the table entity to write.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Configuration

The following table explains the properties that you can set on the options object passed to the output.table() method.

Property Description
tableName The name of the table to which to write.
partitionKey The partition key of the table entity to write.
rowKey The row key of the table entity to write.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Configuration

The following table explains the binding configuration properties that you set in the function.json file.

function.json property Description
type Must be set to table. This property is set automatically when you create the binding in the Azure portal.
direction Must be set to out. This property is set automatically when you create the binding in the Azure portal.
name The variable name used in function code that represents the table or entity. Set to $return to reference the function return value.
tableName The name of the table to which to write.
partitionKey The partition key of the table entity to write.
rowKey The row key of the table entity to write.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Connections

The connection property is a reference to environment configuration that specifies how the app should connect to your table service. It 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

To obtain a connection string for tables in Azure Table storage, follow the steps shown at Manage storage account access keys. To obtain a connection string for tables in Azure Cosmos DB for Table, follow the steps shown at the Azure Cosmos DB for Table FAQ.

This connection string should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage". If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

Identity-based connections

If you're using the Tables API extension, instead of using a connection string with a secret, you can have the app use an Microsoft Entra identity. This only applies when accessing tables in Azure Storage. To use an identity, you define settings under a common prefix that maps to the connection property in the trigger and binding configuration.

If you're setting connection to "AzureWebJobsStorage", see Connecting to host storage with an identity. For all other connections, the extension requires the following properties:

Property Environment variable template Description Example value
Table Service URI <CONNECTION_NAME_PREFIX>__tableServiceUri1 The data plane URI of the Azure Storage table service to which you're connecting, using the HTTPS scheme. https://<storage_account_name>.table.core.windows.net

1 <CONNECTION_NAME_PREFIX>__serviceUri can be used as an alias. If both forms are provided, the tableServiceUri form is used. The serviceUri form can't be used when the overall connection configuration is to be used across blobs, queues, and/or tables.

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

The serviceUri form can't be used when the overall connection configuration is to be used across blobs, queues, and/or tables in Azure Storage. The URI can only designate the table service. As an alternative, you can provide a URI specifically for each service under the same prefix, allowing a single connection to be used.

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. For most Azure services, this means you 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'll need to create a role assignment that provides access to your Azure Storage table service at runtime. Management roles like Owner aren't sufficient. The following table shows built-in roles that are recommended when using the Azure Tables extension against Azure Storage in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles (Azure Storage1)
Input binding Storage Table Data Reader
Output binding Storage Table Data Contributor

1 If your app is instead connecting to tables in Azure Cosmos DB for Table, using an identity isn't supported and the connection must use a connection string.

Usage

The usage of the binding depends on the extension package version, and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

Choose a version to see usage details for the mode and version.

When you want the function to write to a single entity, the Azure Tables output binding can bind to the following types:

Type Description
A JSON serializable type that implements [ITableEntity] Functions attempts to serialize a plain-old CLR object (POCO) type as the entity. The type must implement [ITableEntity] or have a string RowKey property and a string PartitionKey property.

When you want the function to write to multiple entities, the Azure Tables output binding can bind to the following types:

Type Description
T[] where T is one of the single entity types An array containing multiple entities. Each entry represents one entity.

For other output scenarios, create and use a TableClient with other types from Azure.Data.Tables directly. See Register Azure clients for an example of using dependency injection to create a client type from the Azure SDK.

There are two options for outputting a Table storage row from a function by using the TableStorageOutput annotation:

Options Description
Return value By applying the annotation to the function itself, the return value of the function persists as a Table storage row.
Imperative To explicitly set the table row, apply the annotation to a specific parameter of the type OutputBinding<T>, where T includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.

Set the output row data by returning the value or using context.extraOutputs.set().

To write to table data, use the Push-OutputBinding cmdlet, set the -Name TableBinding parameter and -Value parameter equal to the row data. See the PowerShell example for more detail.

There are two options for outputting a Table storage row message from a function:

Options Description
Return value Set the name property in function.json to $return. With this configuration, the function's return value persists as a Table storage row.
Imperative Pass a value to the set method of the parameter declared as an Out type. The value passed to set is persisted as table row.

For specific usage details, see Example.

Exceptions and return codes

Binding Reference
Table Table Error Codes
Blob, Table, Queue Storage Error Codes
Blob, Table, Queue Troubleshooting

Next steps