Microsoft learn: Write data with output bindings

Michael Guillaume 26 Reputation points
2020-12-12T16:23:05.653+00:00

I am following Microsoft Learn path :
https://learn.microsoft.com/en-us/learn/modules/chain-azure-functions-data-using-bindings/7-write-data-with-output-bindings-portal-lab?pivots=javascript

I am trying to use the input binding for CosmoDB, in the example of Microsoft, the Input binding of CosmoDB is done through query string. On the "Try it", I don't see any http request with parameters, only JSON parameter into the request body

Can someone explain my what's happening ? I am confuse, how the ID binding is made from the request body ?

Remarks: I did the exercise on NET Core azure function

    public class Function1  
    {  
        //http://localhost:7071/api/CosmoDbActionsSandbox/blog/blog/  
        [FunctionName(nameof(CosmoDbActionsSandbox))]  
        public async Task<IActionResult> CosmoDbActionsSandbox(  
            [HttpTrigger(AuthorizationLevel.Function, "get", "post",  
                Route = nameof(CosmoDbActionsSandbox) + "/{id}")] HttpRequest req,  
            [CosmosDB(databaseName: "func-io-learn-db",  
                collectionName: "Bookmarks",  
                ConnectionStringSetting = "CosmosDBConnection",  
                Id = "{id}",  
                PartitionKey = "{id}")] Bookmark bookmark,  
            [CosmosDB(databaseName: "func-io-learn-db",  
                collectionName: "Bookmarks",  
                ConnectionStringSetting = "CosmosDBConnection",  
                PartitionKey = "{id}")] IAsyncCollector<Bookmark> bookmarkOutput,  
            ILogger log)  
        {  
            log.LogInformation("C# HTTP trigger function processed a request.");  
  
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
            Bookmark newBookmark = JsonConvert.DeserializeObject<Bookmark>(requestBody);  
  
            if (bookmark != null)  
                return new StatusCodeResult(422);  
            else  
            {  
                await bookmarkOutput.AddAsync(newBookmark);  
                return new OkObjectResult(newBookmark);  
            }  
        }  
    }  
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,333 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,320 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jaliya Udagedara 2,736 Reputation points MVP
    2020-12-13T08:43:59.733+00:00

    This pattern is called binding expressions: Azure Functions binding expression patterns

    When a trigger payload is JSON, you can refer to its properties in a configuration for other bindings in the same function and in function code. For C# and F#, you need a class that defines the fields to be deserialized, I believe your Bookmark class has a property named 'id'. In JavaScript as in the exercise you are following, JSON deserialization is automatically performed.

    Hope this helps!

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Michael Guillaume 26 Reputation points
    2020-12-14T10:36:15.077+00:00

    Thank you JaliyaUdagedara for this answer,

    Here is the full code to make it work, the difference is to replace the "HttpRequest req" parameter in the HttpTrigger by the type to bind to (In this case Bookmark)

        public class Bookmark
        {
            [JsonProperty("id")]
            public string Id { get; set; }
    
            [JsonProperty("url")]
            public string Url { get; set; }
    
        }
    
    
        public class Function1
        {
            /// <summary>
            /// Check if the bookmark exist, if not create a new one
            /// </summary>
            /// <example>
            /// http://localhost:7071/api/CosmoDbActionsSandbox
            ///
            /// Body of the request
            /// {
            ///    "id":"blog",
            ///    "url": "myURL"
            /// }
            /// </example>
            /// <returns></returns>
            [FunctionName(nameof(CosmoDbActionsSandbox))]
            public async Task<IActionResult> CosmoDbActionsSandbox(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post",
                    Route = nameof(CosmoDbActionsSandbox)/* + "/{id}"*/)] /*HttpRequest req,*/ Bookmark newBookmark, 
                [CosmosDB(databaseName: "func-io-learn-db",
                    collectionName: "Bookmarks",
                    ConnectionStringSetting = "CosmosDBConnection",
                    Id = "{id}",
                    PartitionKey = "{id}")] Bookmark bookmark,
                [CosmosDB(databaseName: "func-io-learn-db",
                    collectionName: "Bookmarks",
                    ConnectionStringSetting = "CosmosDBConnection",
                    PartitionKey = "{id}")] IAsyncCollector<Bookmark> bookmarkOutput,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                if (bookmark != null)
                    return new StatusCodeResult(422); //already exist
                else
                {
                    await bookmarkOutput.AddAsync(newBookmark);
                    return new OkObjectResult(newBookmark);
                }
            }
        }
    
    0 comments No comments