2
votes

Trying to build a couple simple http Azure functions. One would take a POST from a web app, containing a JSON body, and save that as a document in CosmosDB (DocumentDB). The other sends a GET request with a parameter, which reads that document from the database and returns it as JSON.

I have my DocumentDB collection all setup and ready.

Every example I find that comes close always has some slight difference, like outputting to a queue, so that the example is not quite what I need.

2

2 Answers

2
votes

Trying to build a couple simple http Azure functions. One would take a POST from a web app, containing a JSON body, and save that as a document in CosmosDB (DocumentDB).

To store data in Cosmos DB from HttpTrigger Azure functions app, you can refer to the following sample code that works fine on my side.

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, out object taskDocument, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    MyData md=req.Content.ReadAsAsync<MyData>().Result;
    taskDocument  = new {
        name = md.name,
        task = md.task,
        duedate = md.duedate
    };


   if (name != "") {
        return req.CreateResponse(HttpStatusCode.OK);
    }
    else {
        return req.CreateResponse(HttpStatusCode.BadRequest);
    }
}

public class MyData{
    public string name { get; set;}
    public string task { get; set;}
    public string duedate { get; set;}
}

enter image description here

enter image description here

The other sends a GET request with a parameter, which reads that document from the database and returns it as JSON.

To retrieve data from Cosmos DB and return it as JSON via Azure functions app, please refer to the following sample.

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "documents/{name}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "xxxdocumentdbtest",
      "collectionName": "testcoll",
      "sqlQuery": "SELECT * FROM c where c.name = {name}",
      "connection": "xxxx_DOCUMENTDB",
      "direction": "in"
    }
  ],
  "disabled": false
}

run.csx

#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;

public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<MyData> inputDocument, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    MyData md = inputDocument.FirstOrDefault();

    log.Info(md.task);

    var val = JsonConvert.SerializeObject(md);

    return req.CreateResponse(HttpStatusCode.OK, val);
}

public class MyData{
    public string name { get; set;}
    public string task { get; set;}
    public string duedate { get; set;}
}

enter image description here

0
votes

Are you asking how you should return JSON?

This is the contents of one of my Azure Functions. First, I try to retrieve the data I want (GetVotes()). Afterwards I change this data to a format I want to return to the client (CreateResponse()) and return in to the client while serializing it to JSON.

    [FunctionName("Status")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter logWriter)
    {
        Status.log = logWriter;
        Status.log.Info("C# HTTP trigger function processed a request.");

        var votes = await GetVotes();
        var response = CreateResponse(votes);

        return req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(response));
    }

    private static List<ViewModel.Vote> CreateResponse(IEnumerable<Entities.Vote> votes)
    {
        var voteCount = new Dictionary<string, int>();
        foreach (var vote in votes)
        {
            Status.log.Info($"Found language `{vote.Language}`.");
            if (voteCount.ContainsKey(vote.Language))
            {
                voteCount[vote.Language]++;
            }
            else
            {
                voteCount.Add(vote.Language, 1);
            }
        }

        var result = new List<ViewModel.Vote>();
        foreach (var languageVotes in voteCount)
        {
            result.Add(new ViewModel.Vote(languageVotes.Key, languageVotes.Value));
        }
        return result;
    }

Of course, you can do this with any type of object, if the object can be serialized to JSON.

The important part of this snippet is the JsonConvert.SerializeObject(response), which does the actual serializing to a JSON format.