How to delete an item in a CosmosDB from an Azure HTTP Trigger function in C#

Viewed 466

I have a Blazor, Azure Stacic Web App that is using Azure HTTP Trigger Functions to perform CRUD operations on an Azure CosmosDB. I am unsure how to remove a single item from the database? GET and POST actions seem to be well documented for HTTP Trigger Functions but I am struggling to find out how to perform a DELETE on just a single item. I have the id property of the item, so would be choosing the item to be removed by it's id.

For my POST actions I am using the IAsyncCollector object and it's Add method, but there doesn't look to be an equivalent for removing.

This is my first question on StackOverflow so if I need more detail/specifics then please let me know :) . I am also relatively new to Azure Functions so if I am fundamentally misunderstanding something then that would be great to know.

Thank you!

1 Answers

This has already been answered here. However, that is with the func code editor using portal.

You can instead bind an instance of DocumentClient directly to your HTTP trigger function:

[FunctionName("Function1")]
public async Task<IActionResult> DeleteProduct(
    [HttpTrigger(
        authLevel: AuthorizationLevel.Anonymous,
        methods: "delete",
        Route = "products/{productId}")] HttpRequest request,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "products")] DocumentClient client,
    Guid productId)
{
    Uri productUri = UriFactory.CreateDocumentUri("my-database", "products", productId.ToString());
    PartitionKey partitionKey = new PartitionKey("my-partition-key");
    RequestOptions requestOptions = new RequestOptions { PartitionKey = partitionKey };

    ResourceResponse<Document> response = await client.DeleteDocumentAsync(productUri, requestOptions);
    // Use response for something or not...

    return new NoContentResult();
}

The example requires you to have a Cosmos DB connection string configured with the key "CosmosDBConnection". This must be set in local.settings.json for local development:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "CosmosDBConnection": "my-cosmos-db-connection"
  }
}

And in your function app's application settings on portal.

You'll need the following packages to make it work:

  • Microsoft.Azure.Cosmos
  • Microsoft.Azure.WebJobs.Extensions.CosmosDB
Related