John Szatmari
John Szatmari

Reputation: 395

Unable to write to CosmosDB from an Azure Event Hub

I'm working on an Azure Function(2.x) which is triggered by events coming from an Event Hub and writes the received data to a CosmosDB instance. Before I deploy it, I'd like to test it locally and reading the event works flawlessly. However, when I try to write to CosmosDB this error shows up:

"System.Private.CoreLib: Exception while executing function: Functions.EventHubTrigger. Microsoft.Azure.DocumentDB.Core: Message: {"Errors":["One of the specified inputs is invalid"]}"

The database instance was created using the Azure Portal and I added a couple of dummy entries, all of which works fine. What am I doing wrong?

function.json:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "event",
      "direction": "in",
      "eventHubName": "event-hub-name",
      "connection": "event-hub-connection",
      "cardinality": "many",
      "consumerGroup": "$Default"
    },
    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "doc",
      "databaseName": "database-name",
      "collectionName": "test",
      "createIfNotExists": "true",
      "connectionStringSetting": "CosmosDBConnectionString"
    }
  ]
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "storage-key",
    "CosmosDBConnectionString": "AccountEndpoint=document-db-endpoint;AccountKey=account-key;",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "event-hub-connection": "Endpoint=sb://endpoint-name;SharedAccessKeyName=shared-access-key-name;SharedAccessKey=shared-access-key" 
  }
}

host.json:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

__init__.py:

import logging, json

import azure.functions as func


def main(event: func.EventHubEvent, doc: func.Out[func.Document]):

    event_data = event.get_body().decode("utf-8")
    logging.info('Python EventHub trigger processed an event: %s', event_data)

    # json object for testing the DB write operation
    temp = {}
    temp["id"] = 1
    temp["category"] = "feedback"
    temp = json.dumps(temp)

    doc.set(func.Document.from_json(temp))
    logging.info("CosmosDB updated!; Value: ", temp)

Upvotes: 1

Views: 1118

Answers (1)

Matias Quaranta
Matias Quaranta

Reputation: 15603

That error is a HTTP 400, BadRequest. Meaning that something in the payload is not correctly formed JSON or some of your attributes is invalid.

I see your id is a number, but in the REST contract, it's a string. Reference: https://learn.microsoft.com/rest/api/cosmos-db/create-a-document#body

Can you change the id to a string?

Upvotes: 1

Related Questions