| title | Dapr Publish output binding for Azure Functions |
|---|---|
| description | Learn how to provide Dapr Publish output binding data using Azure Functions. |
| ms.topic | reference |
| ms.date | 05/10/2024 |
| ms.author | nigreenf |
| ms.reviewer | hannahhunter |
| ms.subservice | dapr |
| ms.devlang | csharp |
| ms.custom | devx-track-csharp, devx-track-python, devx-track-dotnet, devx-track-extended-java, devx-track-js, build-2024 |
| zone_pivot_groups | programming-languages-set-functions-lang-workers |
The Dapr publish output binding allows you to publish a message to a Dapr topic during a function execution.
For information on setup and configuration details of the Dapr extension, see the Dapr extension overview.
::: zone pivot="programming-language-csharp"
A C# function can be created using one of the following C# modes:
[!INCLUDE dotnet-execution]
The following example demonstrates using a Dapr publish output binding to perform a Dapr publish operation to a pub/sub component and topic.
[FunctionName("PublishOutputBinding")]
public static void Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "topic/{topicName}")] HttpRequest req,
[DaprPublish(PubSubName = "%PubSubName%", Topic = "{topicName}")] out DaprPubSubEvent pubSubEvent,
ILogger log)
{
string requestBody = new StreamReader(req.Body).ReadToEnd();
pubSubEvent = new DaprPubSubEvent(requestBody);
}More samples for the Dapr output publish binding are available in the GitHub repository.
:::code language="csharp" source="~/azure-functions-dapr-extension/samples/dotnet-isolated-azurefunction/OutputBinding/PublishOutputBinding.cs" range="16-25":::
::: zone-end
::: zone pivot="programming-language-java"
The following example creates a "TransferEventBetweenTopics" function using the DaprPublishOutput binding with an DaprTopicTrigger:
@FunctionName("TransferEventBetweenTopics")
public String run(
@DaprTopicTrigger(
pubSubName = "%PubSubName%",
topic = "A")
String request,
@DaprPublishOutput(
pubSubName = "%PubSubName%",
topic = "B")
OutputBinding<String> payload,
final ExecutionContext context) throws JsonProcessingException {
context.getLogger().info("Java function processed a TransferEventBetweenTopics request from the Dapr Runtime.");
}::: zone-end
::: zone pivot="programming-language-javascript"
In the following example, the Dapr publish output binding is paired with an HTTP trigger, which is registered by the app object:
const { app, trigger } = require('@azure/functions');
app.generic('PublishOutputBinding', {
trigger: trigger.generic({
type: 'httpTrigger',
authLevel: 'anonymous',
methods: ['POST'],
route: "topic/{topicName}",
name: "req"
}),
return: daprPublishOutput,
handler: async (request, context) => {
context.log("Node HTTP trigger function processed a request.");
const payload = await request.text();
context.log(JSON.stringify(payload));
return { payload: payload };
}
});The following examples show Dapr triggers in a function.json file and JavaScript code that uses those bindings.
Here's the function.json file for daprPublish:
{
"bindings":
{
"type": "daprPublish",
"direction": "out",
"pubsubname": "messagebus",
"topic": "{topicName}",
"name": "payload"
}
}For more information about function.json file properties, see the Configuration section.
Here's the JavaScript code:
module.exports = async function (context, req) {
context.log("Node HTTP trigger function processed a request.");
context.bindings.payload = { payload: req.body };
context.done(null);
};::: zone-end
::: zone pivot="programming-language-powershell"
The following examples show Dapr triggers in a function.json file and PowerShell code that uses those bindings.
Here's the function.json file for daprPublish:
{
"bindings":
{
"type": "daprPublish",
"direction": "out",
"name": "pubEvent",
"pubsubname": "%PubSubName%",
"topic": "B"
}
}For more information about function.json file properties, see the Configuration section.
In code:
using namespace System
using namespace Microsoft.Azure.WebJobs
using namespace Microsoft.Extensions.Logging
using namespace Microsoft.Azure.WebJobs.Extensions.Dapr
using namespace Newtonsoft.Json.Linq
# Example to use Dapr Service Invocation Trigger and Dapr State Output binding to persist a new state into statestore
param (
$subEvent
)
Write-Host "PowerShell function processed a TransferEventBetweenTopics request from the Dapr Runtime."
# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $subEvent["data"]
$messageFromTopicA = "Transfer from Topic A: $jsonString".Trim()
$publish_output_binding_req_body = @{
"payload" = $messageFromTopicA
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name pubEvent -Value $publish_output_binding_req_body::: zone-end
::: zone pivot="programming-language-python"
The following example shows a Dapr Publish output binding, which uses the v2 Python programming model. To use daprPublish in your Python function app code:
import logging
import json
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="TransferEventBetweenTopics")
@app.dapr_topic_trigger(arg_name="subEvent", pub_sub_name="%PubSubName%", topic="A", route="A")
@app.dapr_publish_output(arg_name="pubEvent", pub_sub_name="%PubSubName%", topic="B")
def main(subEvent, pubEvent: func.Out[bytes]) -> None:
logging.info('Python function processed a TransferEventBetweenTopics request from the Dapr Runtime.')
subEvent_json = json.loads(subEvent)
payload = "Transfer from Topic A: " + str(subEvent_json["data"])
pubEvent.set(json.dumps({"payload": payload}).encode('utf-8'))The following example shows a Dapr Publish output binding, which uses the v1 Python programming model.
Here's the function.json file for daprPublish:
{
"scriptFile": "__init__.py",
"bindings":
{
"type": "daprPublish",
"direction": "out",
"name": "pubEvent",
"pubsubname": "messagebus",
"topic": "B"
}
}For more information about function.json file properties, see the Configuration section.
Here's the Python code:
def main(subEvent,
pubEvent: func.Out[bytes]) -> None:
logging.info('Python function processed a TransferEventBetweenTopics request from the Dapr Runtime.')
subEvent_json = json.loads(subEvent)
payload = "Transfer from Topic A: " + str(subEvent_json["data"])
pubEvent.set(json.dumps({"payload": payload }))::: zone-end
::: zone pivot="programming-language-csharp"
In the in-process model, use the DaprPublish to define a Dapr publish output binding, which supports these parameters:
| function.json property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| PubSubName | The name of the Dapr pub/sub to send the message. | ✔️ | ✔️ |
| Topic | The name of the Dapr topic to send the message. | ✔️ | ✔️ |
| Payload | Required. The message being published. | ❌ | ✔️ |
In the isolated worker model, use the DaprPublish Output to define a Dapr publish output binding, which supports these parameters:
| function.json property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| PubSubName | The name of the Dapr pub/sub to send the message. | ✔️ | ✔️ |
| Topic | The name of the Dapr topic to send the message. | ✔️ | ✔️ |
| Payload | Required. The message being published. | ❌ | ✔️ |
::: zone-end
::: zone pivot="programming-language-java"
The DaprPublishOutput annotation allows you to have a function access a published message.
| Element | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pubSubName | The name of the Dapr pub/sub to send the message. | ✔️ | ✔️ |
| topic | The name of the Dapr topic to send the message. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
::: zone-end
::: zone pivot="programming-language-javascript, programming-language-powershell, programming-language-python"
::: zone-end
::: zone pivot="programming-language-javascript"
The following table explains the binding configuration properties that you set in the code.
| Property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pubsubname | The name of the publisher component service. | ✔️ | ✔️ |
| topic | The name/identifier of the publisher topic. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
The following table explains the binding configuration properties that you set in the function.json file.
| function.json property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pubsubname | The name of the publisher component service. | ✔️ | ✔️ |
| topic | The name/identifier of the publisher topic. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
::: zone-end
::: zone pivot="programming-language-powershell"
The following table explains the binding configuration properties that you set in the function.json file.
| function.json property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pubsubname | The name of the publisher component service. | ✔️ | ✔️ |
| topic | The name/identifier of the publisher topic. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
::: zone-end
::: zone pivot="programming-language-python"
The following table explains the binding configuration properties for @dapp.dapr_publish_output that you set in your Python code.
| Property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pub_sub_name | The name of the publisher event. | ✔️ | ✔️ |
| topic | The publisher topic name/identifier. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
The following table explains the binding configuration properties that you set in the function.json file.
| function.json property | Description | Can be sent via Attribute | Can be sent via RequestBody |
|---|---|---|---|
| pubsubname | The name of the publisher component service. | ✔️ | ✔️ |
| topic | The name/identifier of the publisher topic. | ✔️ | ✔️ |
| payload | Required. The message being published. | ❌ | ✔️ |
::: zone-end
If properties are defined in both Attributes and RequestBody, priority is given to data provided in RequestBody.
See the Example section for complete examples.
To use the Dapr publish output binding, start by setting up a Dapr pub/sub component. You can learn more about which component to use and how to set it up in the official Dapr documentation.
::: zone pivot="programming-language-python"
To use the daprPublish in Python v2, set up your project with the correct dependencies.
-
In your
requirements.textfile, add the following line:azure-functions==1.18.0b3
-
In the terminal, install the Python library.
pip install -r .\requirements.txt -
Modify your
local.setting.jsonfile with the following configuration:"PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
The Python v1 model requires no additional changes, aside from setting up the output pub/sub component.
::: zone-end