Skip to content

Instantly share code, notes, and snippets.

@Rickcau
Last active February 26, 2023 17:39
Show Gist options
  • Save Rickcau/5732ac101c783f6bd9e5026895746f9a to your computer and use it in GitHub Desktop.
Save Rickcau/5732ac101c783f6bd9e5026895746f9a to your computer and use it in GitHub Desktop.
Azure Function API with Cosmos DB Input Binding

HttpTrigger -Cosmos DB API

The HttpTrigger makes it incredibly easy to have your functions executed via an HTTP call to your function. This sample, exposes a function that can get call with an HTTP GET and it will return all Patients from Cosmos DB. It can be used to build a REST API that exposes CRUD operations. You can take this a step further by leveraging APIM. The idea is to create a serverless micro-service CRUD endpoint using Azure functions. This is a much faster way to create an API for backends than writing a Web App. If you need better performance just use the Premimum tier.

How it works

When you call the function, be sure you checkout which security rules you apply. If you're using an apikey, you'll need to include that in your request. For this example, I simply use anonymous.

Learn more

Documentation

The files in the setup/FunctionApp folder are a functioning and were created directly in the Portal, not via VS Code, so the files that are needed for this are run.csx, function.json and readme.md.

Steps to get this working.

Setup Cosmos DB

  1. Create a Cosmos DB account
  2. Create a DB called PatientsDB
  3. Create a Collection called Patients-Containers
  4. Upload the setup/Cosmos-Seed-Data.JSON data into the Patients-Containters Items (this seeds Cosmos with sample data).

Create the HTTP Trigger Azure Function

  1. Navigate to portal.azure.com and create a new Azure Function
  2. Navigate to the Code + Test Blade and select the Run.csx file and replace the contents with the Run.csx file found in this gist.
  3. Now, select the function.json file and replace the contents of it with the file found in this gist and do the same for the readme.md
  4. Now, time to test it. If you have everything setup correctly, it will return all JSON documents from Cosmos that have a type = patient.

The result set wull look something like this:

    [
      {
        "id": "1",
        "Patient_Id": "1",
        "type": "patient",
        "name": "Steve Smith",
        "phone": "704-555-1212",
        "email": "steve.smith@contoso.com",
        "country": "USA",
        "_rid": "uatfAJuYoXYBAAAAAAAAAA==",
        "_self": "dbs/uatfAA==/colls/uatfAJuYoXY=/docs/uatfAJuYoXYBAAAAAAAAAA==/",
        "_etag": "\"0c0011ba-0000-0100-0000-63fa7f320000\"",
        "_attachments": "attachments/",
        "_ts": 1677360946
      },
      {
        "id": "2",
        "Patient_Id": "2",
        "type": "patient",
        "name": "David Smith",
        "phone": "704-555-1212",
        "email": "david.smith@contoso.com",
        "country": "USA",
        "_rid": "uatfAJuYoXYCAAAAAAAAAA==",
        "_self": "dbs/uatfAA==/colls/uatfAJuYoXY=/docs/uatfAJuYoXYCAAAAAAAAAA==/",
        "_etag": "\"0c0012ba-0000-0100-0000-63fa7f320000\"",
        "_attachments": "attachments/",
        "_ts": 1677360946
      },
[
{
"id": "1",
"Patient_Id": "1",
"type": "patient",
"name": "Steve Smith",
"phone": "704-555-1212",
"email": "steve.smith@contoso.com",
"country": "USA"
},
{
"id": "2",
"Patient_Id": "2",
"type": "patient",
"name": "David Smith",
"phone": "704-555-1212",
"email": "david.smith@contoso.com",
"country": "USA"
},
{
"id": "3",
"Patient_Id": "3",
"type": "patient",
"name": "Bob Smith",
"phone": "704-555-1212",
"email": "bob.smith@contoso.com",
"country": "USA"
},
{
"id": "4",
"Patient_Id": "4",
"type": "patient",
"name": "Sue Smith",
"phone": "704-555-1212",
"email": "sue.smith@contoso.com",
"country": "USA"
},
{
"id": "5",
"Patient_Id": "5",
"type": "patient",
"name": "Joe Smith",
"phone": "704-555-1212",
"email": "joe.smith@contoso.com",
"country": "USA"
},
{
"id": "469517c7-bae9-4e38-9506-561cd955f3d4",
"Patient_Id": "5",
"type": "status",
"name": "Joe Smith",
"status": "feeling ok",
"symptoms": [ "High Fever", "Left Arm Sore" ],
"country": "USA"
},
{
"id": "99e8a16e-9ee1-471d-b1b4-31c6da62405d",
"Patient_Id": "4",
"type": "status",
"name": "Sue Smith",
"status": "feeling great",
"symptoms": [ "Low Fever", "Right Arm Sore" ],
"country": "USA"
}
]
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"name": "patients",
"databaseName": "PatientsDB",
"collectionName": "Patients-Containers",
"connectionStringSetting": "cosmos-power-plat-train-rdc2023_DOCUMENTDB",
"sqlQuery": "select * from c where c.type=\"patient\"",
"direction": "in",
"type": "cosmosDB"
}
]
}
#r "Newtonsoft.Json"
using System.Net;
using System.Collections;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log, IEnumerable<dynamic> patients)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(patients);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment