With Azure API Management (APIM), now you can send/publish messages directly
to Azure Service Bus. Note: at the time of writing this post, this feature is
still in preview. I am very excited for this feature, because now we can have
a simple architecture, we don't need a separate backend code/service to
send/publish messages.
This is done via the send-service-bus-message policy.
Let's have a look.
I have a Service Bus namespace and a user assigned Managed Identity. The
Managed Identity has the Azure Service Bus Data Sender role assigned
to the namespace. In the Service Bus namespace, I have a topic: sbt-apim.
In my APIM, I have an API with an operation configured with the following
policy.
<!-- Add policies as children to the <inbound>, <outbound>, <backend>, and <on-error> elements --> <policies> <!-- Throttle, authorize, validate, cache, or transform the requests --> <inbound> <send-service-bus-message topic-name="sbt-apim" namespace="<ServiceBusNamespaceName>.servicebus.windows.net" client-id="<ManagedIdentityClientId>"> <message-properties> <message-property name="TenantId">@(context.Request.Headers.GetValueOrDefault("x-tenantId",""))</message-property> </message-properties> <payload> @(context.Request.Body.As<string>(preserveContent: true)) </payload> </send-service-bus-message> <return-response> <set-status code="202" reason="Accepted" /> <set-header name="Content-Type" exists-action="override"> <value>application/json</value> </set-header> <set-body>{ "status": "Message Accepted" }</set-body> </return-response> </inbound> <!-- Control if and how the requests are forwarded to services --> <backend> <base /> </backend> <!-- Customize the responses --> <outbound> <base /> </outbound> <!-- Handle exceptions and customize error responses --> <on-error> <base /> </on-error> </policies>
Here I am using the send-service-bus-message policy in the inbound section to publish messages to a Service Bus
topic. The client-id refers to the user assigned Managed Identity. You can also add custom
message properties. Here I am passing the value of x-tenantId header as a custom property for demo purposes. Since we don't need a
backend service, I am using return-response to immediately return a 202 Accepted response.
Let's test this.
curl 'https://<APIM_BASE_URL>/messaging/publish' ` --header 'x-tenantId: cfecb449-b568-4d0f-b24f-ea9762fb2bf6' ` --header 'Content-Type: application/json' ` --data '{ "firstName": "John", "lastName": "Doe" }'
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment