How to use azure cosmos within azure function app?

Ashraqat Sheta 20 Reputation points
2023-09-02T11:02:51.84+00:00

I am trying to use Microsoft.Azure.Cosmos within azure function app with binding CosmosClient as an input but i am getting error messages and it isn't working.

Can you help me to get it work, please?

User's image

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,010 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,640 questions
{count} votes

Accepted answer
  1. navba-MSFT 24,625 Reputation points Microsoft Employee
    2023-09-04T13:30:12.1766667+00:00

    @Ashraqat Sheta Thanks for clarifying. I just wrote a sample code that receives an HTTP request and writes the request body to a Cosmos DB container. The function is triggered by an HTTP request and uses the [HttpTrigger] attribute to define the trigger. It uses the cosmosclient to perform the add, update and delete operation:

    • You need to create an Azure Function APP project in your Visual Studio with HTTP Trigger.
    • Then ensure that you install Microsoft.Azure.Cosmos package via nuget.
    • please update the cosmos DB connection details in the code.
    • Then you can run the Function app.
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using Microsoft.Azure.Cosmos;
    using System.Configuration;
    
    namespace CosmosClientCRUDFuncApp
    {
        public static class Function1
        {
            
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                string operation = data?.operation;
    
                string endpoint = "https://mycosmosdb.documents.azure.com:443/";
                string key = "v3NJKDr7P0pNqt**********************zZwACDbnCNHTw==";
                CosmosClient client = new CosmosClient(endpoint, key);
                string databaseName = "testdb";
                string containerName = "testcontainer";
                Container container = client.GetContainer(databaseName, containerName);
    
                if (operation == "add")
                {
                    string description = data?.description;
                    if (description != null)
                    {
                        dynamic document = new { Description = description, id = Guid.NewGuid().ToString() };
                        await container.CreateItemAsync(document);
                        log.LogInformation("C# HTTP trigger function processed a request to add a document.");
                        return new OkResult();
                    }
                    else
                    {
                        return new BadRequestObjectResult("Please provide description for adding a document.");
                    }
                }
                else if (operation == "update")
                {
                    string id = data?.id;
                    string description = data?.description;
                    if (id != null && description != null)
                    {
                        try
                        {
                            ItemResponse<dynamic> response = await container.ReadItemAsync<dynamic>(id, new PartitionKey(id));
                            dynamic document = response.Resource;
                            document.Description = description;
                            await container.ReplaceItemAsync(document, id, new PartitionKey(id));
                            log.LogInformation("C# HTTP trigger function processed a request to update a document.");
                            return new OkResult();
                        }
                        catch (Exception ex)
                        {
                            log.LogError(ex, "Error updating document");
                            return new StatusCodeResult(500);
                        }
                    }
    
                   
                    else
                    {
                        return new BadRequestObjectResult("Please provide both id and description for updating a document.");
                    }
                }
                else if (operation == "delete")
                {
                    string id =  data?.id; 
                    if (id != null) 
                    {
                        try
                        {
                            ItemResponse<dynamic> response = await container.DeleteItemAsync<dynamic>(id, new PartitionKey(id));
                            log.LogInformation("C# HTTP trigger function processed a request to delete a document.");
                            return new OkResult();
                        }
                        catch (Exception ex)
                        {
                            log.LogError(ex, "Error deleting document");
                            return new StatusCodeResult(500);
                        }
                    } 
                    else
                    { 
                        return new BadRequestObjectResult("Please provide id for deleting a document."); 
                    }
                }
                else 
                {
                    return new BadRequestObjectResult("Please provide a valid operation (add, update, or delete)."); 
                }
            }
        }
    }
    

    To send an HTTP trigger request to this function app from Postman, you can follow these steps:

    • Open Postman and create a new request.
    • Set the request method to POST.
    • Set the request URL to the URL of your function app. This should be in the format https://localhost:port/api/<function-name>.
    • In the request body, select the raw option and set the content type to JSON.
    • For the add operation, you can set the request body to:
    {
        "operation": "add",
        "description": "This is a test document."
    }
    
    {
        "operation": "update",
        "id": "<document-id>",
        "description": "This is an updated test document."
    }
    
    • For the delete operation, you can set the request body to:
    {
        "operation": "delete",
        "id": "<document-id>"
    }
    
    • This should send an HTTP trigger request to your function app and perform the specified operation.

    If you have any follow-up questions, please do let me know. I would be happy to help.

    ** Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.