---
title: "Making a CRUD API using Azure Functions and Azure Cosmos DB"
description: "Learn how to make a wishlist API using Azure Functions and Azure Cosmos DB."
authors:
  - name: "Samson Amaugo"
    url: "https://auth0.com/blog/authors/samson-amaugo/"
date: "Dec 29, 2020"
category: "Developers,Tutorial,Azure"
tags: ["javascript", "azure", "cosmos-db", "serverless"]
url: "https://auth0.com/blog/making-crud-api-with-azure-functions/"
---

# Making a CRUD API using Azure Functions and Azure Cosmos DB



As serverless deployment is becoming popular, equipping yourself with some serverless skills will be paramount. In this article, you will learn how to build a [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) API using Azure Functions and Azure Cosmos DB 🤩.  

## Why Go Serverless with Azure Functions
From [Microsoft's site](https://docs.microsoft.com/en-us/azure/azure-functions/), Azure Functions is a serverless compute service ([Function as a service](https://en.wikipedia.org/wiki/Function_as_a_service)) provided by Azure, Microsoft's cloud service. It lets you run event-triggered code without having to provision or manage any infrastructure explicitly. It contrasts with the classic approach that requires setting up your server, maintaining it, and taking full responsibility for securing it.

Hosting your code on Azure Functions provides you with some cool benefits:  

- **Cost-effective**: Using Azure Functions is probably cheaper for a medium-sized project than running your back-end logic on a dedicated server. In fact, after a function executes, it stops consuming resources, and you are only billed for the number of resources used.
Azure Functions only run when triggered by an event. Various services can trigger an Azure Function to run, such as an HTTP request, a Timer, an Azure Blob storage upload, etc. 
- **Focus on app logic**: Since Azure handles the work of provisioning or maintaining a server, you can dedicate your time more to developing the application logic. This boosts productivity.

## Setting up Azure Functions
Let's take a concrete look at how Azure Functions work by building a CRUD API to manage a wishlist.

As a first step, go to the [Azure portal](https://portal.azure.com/).

>You need an active Azure subscription to use the cloud services on Azure, including Azure Functions.

It is good practice to wrap all your resources inside a resource group. This makes deleting all used resources inside a resource group easy. So click on `Resource groups` icon on your Azure dashboard, as shown below.

![Azure resource groups](https://images.ctfassets.net/23aumh6u8s0i/4ajgQilMtgmJ2i4rGh28g8/e23665e38aa37728a67a05e75dc123ad/azure-resource-groups)  

Next, click on the `Add` button in the *Resource groups* page to create a resource group and wait for the *Create a resource group* page to load.  

![Add new Azure resource group](https://images.ctfassets.net/23aumh6u8s0i/32lfuOvRfPJXKn4wpefoya/bfe3c4e07dce4f56ed7ad20708dcb21d/add-new-azure-resource-group)  

In the `Resource group` input field, you can the name for your resource group. In this tutorial, I will use `crudtutorial` as the resource group's name. You can also select any region closer to where you live from the `Region` field. I will leave that field as it is and click on the `Review + create` button.  

![Define new Azure resource group](https://images.ctfassets.net/23aumh6u8s0i/5ZdEHmFeQ9Rs9xIM32Nh0r/dde7a50f91d97398597142268156eb50/define-new-azure-resource-group)  

After your settings have been reviewed and validated, the `Review + create` button will change to `Create`. Finally, click on the `Create` button to create your resource group.

![Create new Azure resource group](https://images.ctfassets.net/23aumh6u8s0i/2GXfQ2xswvJhYpPUyXGsD1/73076e38b61e720878a33677ec73321e/create-new-azure-resource-group)  

After the resource group has been created, you will be redirected back to the *Resource group* page. Click on the `crudtutorial` resource group or whatever name you chose for your resource group.

The `crudtutorial` resource group page will open. Click on the `Add` button to add a resource to the resource group, as shown in the following image:

![Add Azure resource to resource group](https://images.ctfassets.net/23aumh6u8s0i/1lV4087yT6pT7nmCPATGRE/99291140c7ff2107d8e1bb66922e25b7/add-azure-resource-to-resource-group)  

You will be redirected to a search page for selecting the resource to be created. You can either search for `Function App` in the search field (`a`) or select `Function App` from the list of popular resources (`b`).

![Search Azure Function App](https://images.ctfassets.net/23aumh6u8s0i/1jljtL86gdDoAZeQvRwqoi/c8d15b1d20c9f4385cdce5c6e4756da6/search-azure-function-app)  

The *Create Function App* page opens. Configure the following settings, as depicted by the image below:

1. Assign a unique name to your Function App. I'm using `swacblooms` in the Function App example I'm building. This is also the name that will be prepended to `.azurewebsites.net` to form the Function App domain name (e.g., `swacblooms.azurewebsites.net`).
2. Select *Node.js* as the `Runtime stack` since the function logic will be written in JavaScript.
3. Choose *12 LTS* or any other version as the Node.js version. 
4. Select any region of your choice, preferably a region closer to where you are.
5. Finally, click on the `Review + create` button, wait for validation, and then continue by clicking on the `Create` button.

![Create Function App](https://images.ctfassets.net/23aumh6u8s0i/j1KcQZnpRM9ELyJVzGDkB/1be62af5a4997880f5cd2e2e8d327f14/create-function-app)  

Wait for the required resources for your Function App are provisioned. When the `Go to resource` button becomes active, click on it to navigate to the newly created Function App dashboard.  

![Edit Function App](https://images.ctfassets.net/23aumh6u8s0i/7cDrKMctF61jvXrtLHjMuY/03b8524401c3dfdd44db8410077612b9/edit-azure-function-app)  

The overview page will display general information related to your Function App.

Now, you can focus on creating the CRUD API for your wishlist. So, click on the `Functions` menu on the left panel.

![Overview of Function App](https://images.ctfassets.net/23aumh6u8s0i/OXpEEbrqwHO34bpMraDpZ/1f2a8a006d45ee8a22ae2fa4e605376b/overview-azure-function-app)  

The CRUD API will be implemented by seven functions:

- `initialize-list`: For generating a sample wishlist in the database.
- `get-list`: For retrieving all the wishlist items from the database.
- `get-a-list-item`: For retrieving a specific wishlist item from the database.
- `delete-list-items`: For deleting all the wishlist items in the database.
- `delete-a-list-item`: For deleting a wishlist item from the database.
- `create-a-list-item`: For inserting a new wishlist item to the database.
- `update-a-list-item`: For updating a wishlist item in the database.

To start, click on the `Add` button to create a function. A right panel will slide in containing the required fields needed to configure the function, as you can see in the following image.  

![Add function to Azure Functions App](https://images.ctfassets.net/23aumh6u8s0i/5dmOL1snL6iu7T76AafGtP/5a65aa8e2ba7896f96dd0b7f4ddc7c1d/add-function-to-azure-function-app)  

On the right panel, you see various available templates to bootstrap your function. Since this tutorial is centered on making a CRUD API triggered through an HTTP request, select `HTTP trigger` as the template to use. 

![HTTP trigger template](https://images.ctfassets.net/23aumh6u8s0i/2TjCmE8tTN2gFrBHx7Hyfu/76fd0c4366320692564ec163a13fd49a/http-trigger-template)  

Scroll down a little bit on the right panel, and you will see the `New Function` field, which allows you to provide the function's name.

1. Clear the default function name and replace it with the name of the first function to create, i.e.,  `initialize-list`.
2. In the `Authorization level` field, select `Anonymous`. This setting will allow you to call the function without attaching an [authorization token](https://auth0.com/docs/tokens/access-tokens) to the request.
3. Finally, click on the `Add` button.

![Define function name](https://images.ctfassets.net/23aumh6u8s0i/7o9u4DutSufVnFf7mMEFGO/25a379fc5abf3948addbd41075cd2579/define-function-name)

You will be redirected to the `initialize-list` function dashboard.

Instead of writing the `initialize-list` function logic right now, you will create all the functions first. So, click on the Function App's name on the header section, as shown in the following screenshot:

![Select other functions](https://images.ctfassets.net/23aumh6u8s0i/01dVEsBhyPQODleQr1hG5A/e20c7529fbff34d741ce5ce890a5c074/select-other-functions)


You will see the `initialize-list` function in the general Function App dashboard.

Follow the steps above to create the remaining functions:  `get-list`, `get-a-list-item`, `delete-list-items`, `delete-a-list-item`, `create-a-list-item`, and `update-a-list-item`  

> Remember to set the trigger to `HTTP` and the authorization level to `Anonymous` during the creation of the other functions. 

At the end of this activity, you will get the following function list:

![Function list](https://images.ctfassets.net/23aumh6u8s0i/4jPvX159uZqPewS4WvdrVS/d895945483e636f2584b778a1cf63f20/function-list)


You will come back here to set up the logic for all the functions. However, since those functions need to access the database, you need to set it up first. So the next step will be setting up Azure Cosmos DB.

## Azure Cosmos DB
Azure Cosmos DB is a Microsoft serverless Database. It is very efficient in areas that require low latency performance. It is also cost-effective, letting you pay for only what you use.
An awesome Azure Cosmos DB feature is that it supports several APIs to interact with it. So if you have some knowledge of a database like MongoDB, you don't need to learn a new database query language. You can still make use of the MongoDB syntax to interact with Cosmos DB 😎.

 Currently, Azure Cosmos DB supports these APIs: 

 - The native Core (SQL) API
 -  API for MongoDB
 - Cassandra API
 - Gremlin API
 - Table API

## Setting up Azure Cosmos DB
Move back to the [Azure portal homepage](https://portal.azure.com/) and click on the resource group you created (`crudtutorial`  in this tutorial's example).

![Select resource group](https://images.ctfassets.net/23aumh6u8s0i/7fssZoOQFjwvEWdrF8CMHV/8fd0be91c8f4f0ef7f95dcaced232f77/select-resource-group)

Click on the `Add` button to create a resource, and then search for `Azure Cosmos DB`. As before, you can use the search field (`a`) or select from the popular resource list (`b`).

![Create Cosmos DB resource](https://images.ctfassets.net/23aumh6u8s0i/1ba75ZXvid14TwjKVhfI0Y/4c3fa5013964ae04c18f279d11c27137/create-cosmos-db-resource)

In the *Create Azure Cosmos DB Account* page, ensure that you choose the right resource group (`a`) and assign an account name to your database (`b`), `swacbloomsdb` in the example shown in the image below. Since this tutorial uses MongoDB's API, select `Azure Cosmos DB for MongoDB API` in the API field (`c`).
You can leave the other fields with their default values.

![Setting up Cosmos DB](https://images.ctfassets.net/23aumh6u8s0i/3b7klhBnKPrYUsBfFwXBNR/4f8315968ce7ff84f3cc4e9e05c4618f/setting-up-cosmos-db)

As usual, click on the `Review + create` button to create your database resource and wait for your configuration to be validated. Once your configuration validation is successful, click on the `Create` button to finalize the required resource provisioning.

Wait for the `Go to resource` button to display, and click on it to navigate to the Cosmos DB overview dashboard:

![Cosmos DB dashboard](https://images.ctfassets.net/23aumh6u8s0i/3c59zCwiwoKqEK9RnDtCQ5/1804cbefbcfdf8ef4114d86167d3aec6/cosmos-db-dashboard)

In the dashboard, click on the `Connection String` menu option in the left panel (`a`) and copy the value of the `PRIMARY CONNECTION STRING` field (`b`). Paste it somewhere as this will be used in your Azure Function.

## Setting up Your Azure Function Logic
Now that you have the connection string for the database, the next step is to make the previously created functions working. So, again, go to the [Azure homepage](https://portal.azure.com/) and select the `crudtutorial` resource group.

 In the list of the available resources, select your Function App (`swacblooms`):

![Select Azure Function App](https://images.ctfassets.net/23aumh6u8s0i/2wPIAHZDnPDeVQZ4Pg7b5v/f4f9e6d0dc3a90036e14060c7f8346fd/select-azure-function-app)

There are various ways of writing the logic for your Azure Function. In this tutorial, you will use the _App Service Editor_. It allows you to write your app logic directly on the web. That means you don't need to use a local editor or an extra tool. You get to have an all in one experience of developing your product directly on Azure😎.

On the left panel of the `crudtutorial` Function App, scroll down until you see the `App Service Editor` menu option and click on it.

![Select App Service Editor](https://images.ctfassets.net/23aumh6u8s0i/14atMwGMNAvJjFTiHiGF6c/17cad7e99cce38f8d68f57f86a2eee6c/select-app-service-editor)

Now, click on the `Go ->` button to enter the editor interface.

![Go to App Service Editor](https://images.ctfassets.net/23aumh6u8s0i/N05gDKTXIP1ZIEYrT58Zm/e7beb0c8a650f89c30f4002ec529a929/go-to-app-service-editor)

In the online editor, you should see the folders of the previously created functions. Click on the `console` button, as shown in the screenshot below. This is needed to use the online terminal to install some required dependencies.

![Azure App Service Editor](https://images.ctfassets.net/23aumh6u8s0i/5HaoUcnx3VdI37WJRaWc6C/be176e1209d076007454016e322c7973/azure-app-service-editor)



You need to install two Node.js dependencies:

- **MongoDB**: To enable you to use MongoDB's API to interact with Cosmos DB.
- **UUID**: To generate random IDs for the items in the wishlist.

 So run this command in the terminal to install these dependencies.

``` bash  
 npm install mongodb uuid
```

![Install dependencies](https://images.ctfassets.net/23aumh6u8s0i/1vjCtiRcisDaZ3pSd073Wz/2cedeae67a0cc8a9e7b389217ca6f03b/install-dependencies)

### Defining `initialize-list` logic

Now, click on the `initialize-list` directory and then on the `index.js` file. You are going to add the logic that creates the default wishlist items in the database.
The endpoint to call this function will be in this format: `{Function-URL}/api/wishlist-init`.

The `Function-URL` from the template link above represents the URL for accessing your Azure Function, which you will see soon.

![Define function logic](https://images.ctfassets.net/23aumh6u8s0i/6oqYmXaUdGhx6EtE2CQ3jK/3d8257c1ac3cd9029c1207d23e7d52b8/define-azure-function-logic)


A basic Node.js Azure Function comes in this form:

``` javascript  
module.exports = async function (context, req) {

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}
```

The `context` object is used to pass data between your function and the runtime. To log output to the console, you use the `context.log` function rather than `console.log`. To return a response, you use the `context.res` object.
With that being said, I believe Azure Functions is pretty easy to learn.

Azure creates a default code for you when a function is created. Replace the default code with the following:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");
/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";
const client = new MongoClient(url);

let resetList = [
  {
    _id: uuidv4(),
    name: "Microphone",
    description: "Noise cancelling microphone for recording sessions",
    url:
      "https://cdn.pixabay.com/photo/2020/09/23/02/01/microphone-5594702_960_720.jpg",
  },
  {
    _id: uuidv4(),
    name: "Macbook",
    description: "A laptop with awesome perfomance for dev work",
    url:
      "https://cdn.pixabay.com/photo/2014/09/24/14/29/mac-459196_960_720.jpg",
  },
  {
    _id: uuidv4(),
    name: "Camera",
    description: "Helps to record video sessions",
    url:
      "https://cdn.pixabay.com/photo/2014/05/05/19/53/keyboard-338505_960_720.jpg",
  },
];

module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  await collection.deleteMany({});
  await collection.insertMany(resetList);

  return (context.res = {
    status: 200,
    body: "Initialization successful",
  });
};
```

The code above populates the database with some sample wishlist items, and the pretty awesome thing is that this makes use of MongoDB API to communicate with Cosmos DB 😎. Of course, replace the fake connection string provided in the code above with your actual one.

By default, an HTTP triggered function accepts a request with either a GET or a POST method. So the next step is to configure this `initialize-list` function to accept only a GET request.

Click on the `function.json` file under the `initialize-list` directory. Replace its content with the code below:

``` json 
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist-init",
      "methods": ["get"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

By default, the URL that triggers the execution of this function ends with the name of the function itself (`initialize-list`). The `route` property is used to customize that part of the URL.
The `methods` property defines the HTTP request method that the function accepts.

### Defining `get-list` logic

Next, open the `get-list` directory and click on the `index.js` file to edit it. Clear the default code and paste the following:

``` javascript  
const { MongoClient } = require("mongodb");

const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";const client = new MongoClient(url);

module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  let list = await collection.find({}).toArray();
  return context.res = {
    status: 200,
    body: list,
  };
};
```

The function's endpoint will be called with the GET method and will have this URL template: `{Function-URL}/api/wishlist`.

Also, update the `function.json` file to only accept the GET request. Its content will look this way:

``` json  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist",
      "methods": ["get"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

### Defining `get-a-list-item` logic

Next, click on the `get-a-list-item` directory and select the `index.js` file. Update the default code with the code below:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";
const client = new MongoClient(url);

module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  let obj = await collection.findOne({ _id: req.params.id });
  if (!obj) {
  return  context.res = {
      status: 400,
      body: "not found"
    };
  }
 return context.res = {
    status: 200,
    body: obj,
  };
};
```

The associated endpoint will be called through GET to this URL: `{Function-URL}/api/wishlist/{id}`.

This endpoint requires an `id` parameter, but by default, Azure Functions doesn't accept parameters. For this reason, you need to update the `function.json` file to accept route parameters.

Change the `function.json` file under the `get-a-list-item` directory to accept only requests with a GET method and route parameters. This is how its content will look like:

``` json  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist/{id}",
      "methods": ["get"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

Thanks to the template assigned to the `route` key, the request object in the function can now accept parameters.

### Defining `create-a-list-item` logic

Now, let's continue with the `create-a-list-item` function. Open the related directory, select the `index.js` file, and replace the default code with the following:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";
const client = new MongoClient(url);


module.exports = async function (context, req) {
    await client.connect();
    const database = client.db("crud");
    const collection = database.collection("wishlist");
    let data = { _id: uuidv4(), ...req.body };
    await collection.insertOne(data);

  return (context.res = {
    status: 200,
    body: data,
  });
};
```

The endpoint associated with this function will be called with a POST request to this URL: `{Function-URL}/api/wishlist`. So, let's modify the `function.json` file under the `create-a-list-item` directory to accept only requests with a POST method:

``` javascript  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist",
      "methods": ["post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

### Defining `update-a-list-item` logic

Moving forward, click on the `index.js` file under the `update-a-list-item` directory and update its content as follows:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";const client = new MongoClient(url);

module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  let data = {...req.body };
  let query = {_id:req.params.id}
  let newValues ={$set:data}
 let update = await collection.findOneAndUpdate(query,newValues,{returnOriginal:false})

  if (!update) {
    return (context.res = {
      status: 400,
      body: "found",
    });
  }
context.log(update)
  return (context.res = {
    status: 200,
    body: update.value
  });
};
```

The associated endpoint will be called with a PUT request to this URL template: `{Function-URL}/api/wishlist/{id}`.
As before, this endpoint requires an `id` parameter. So, let's update the `function.json` file to accept the PUT method and route parameters:

``` json  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist/{id}",
      "methods": ["put"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

### Defining `delete-list-items` logic

Open the `delete-list-items` directory and click on the `index.js` file to update it with the following code:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";
const client = new MongoClient(url);

module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  await collection.deleteMany({});
  return (context.res = {
    body: "deleted",
  });
};
```

You will call this function with a DELETE request to this URL: `{Function-URL}/api/wishlist`. So, modify the `function.json` file under the `delete-list-items` directory to accept only DELETE requests:

``` javascript  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist",
      "methods": ["delete"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

### Defining `delete-a-list-item` logic

Finally, update the `index.js` file under the `delete-a-list-item` directory with the following code:

``` javascript  
const { MongoClient } = require("mongodb");
const { v4: uuidv4 } = require("uuid");

/* use the Cosmos DB connection string you copied ealier and replace in the `url` variable */
const url = "mongodb://swacbloomsdb:xxxxxxxxxx@swacbloomsdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@swacbloomsdb@";
const client = new MongoClient(url);


module.exports = async function (context, req) {
  await client.connect();
  const database = client.db("crud");
  const collection = database.collection("wishlist");
  let remove = await collection.deleteOne({ _id: req.params.id });

  if (!remove) {
    return (context.res = {
      status: 400,
      body: {
        message: "not found",
      },
    });
  }
  return (context.res = {
    status: 200,
    body: "deleted"
  });
};
```

The endpoint to call this function will accept DELETE requests to this URL: `{Function-URL}/api/wishlist/{id}`. Once again, you need to configure the function to accept route parameters. So, change the content of the `function.json` file under the `delete-a-list-item` directory, as shown below:

``` json  
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "wishlist/{id}",
      "methods": ["delete"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
```

Now the logic of your functions is ready to run. You just need to test it.
The awesome thing here is that Azure Functions Dashboard provides a testing area that allows you to test your functions directly on Azure.

## Testing Your Azure Function
In your Function App dashboard, click on the `Functions` menu option on the left panel.

![Select Functions menu option](https://images.ctfassets.net/23aumh6u8s0i/wezwhCUcMqdtQaZyEiBJ7/4b8696ba6e54544d7a04f573cf881409/select-functions-menu-option)

Next, click on the `initialize-list` item from the function list.

You will be redirected to the dashboard of the `initialize-list` function. Click on the `Code + Test` menu. And you should see the code you created in the `App Service Editor`.

![Code + Test on function](https://images.ctfassets.net/23aumh6u8s0i/48uhA5G7gWqSv7vOtdUqP4/73660fe227dac83f0cb3ab69729faea4/code-test-on-function)

Click on the `Test/Run` option in the header section of the dashboard. You will see a panel sliding in from the right. There, you can set the required parameters to test your `initialize-list` function, as shown below:

![Testing an Azure Function](https://images.ctfassets.net/23aumh6u8s0i/4C2iFAELOnBtCTi5NRCrN9/3274035a0443892dc92b22afd5b1382d/testing-an-azure-function)

Set the `HTTP method` field to `GET` (`1`) and click on the `Run` button (`2`).

Wait for the function to run, and you should see a 200 HTTP response code with a message saying ` Initialization successful`. At this point, you populated your database with sample wishlist items.

![Successful test on an Azure Function](https://images.ctfassets.net/23aumh6u8s0i/KnNP6nG4WCDYB2DzAf2ek/9c0a33fdc8c0425da1e061402dffeedc/successful-test-on-azure-function)

To get the URL of the API endpoint implemented by this function, right-click on the three dots in the header section and click on the `Get function URL` menu option. 

![Get Azure Function URL](https://images.ctfassets.net/23aumh6u8s0i/6WmlH0Ok3SkmBvWQnkqUEE/3d58ba82b4bc19fc7b270c1c75157b2c/get-azure-function-url)


This option provides you with the full URL associated with this function.

You can proceed the same way to test out the rest of the functions implemented in this tutorial.

That's all. I hope you enjoyed learning how to create a CRUD API  using Azure Functions and Azure Cosmos DB.

<include src="asides/Node" />
