My first experiment with Azure Functions

Avinash Upadhyaya K R
6 min readMar 1, 2021

--

Recently, I came across the Azure Dev Challenge by KonfHub and completed the NodeJS track in it as well. You can find more about this challenge at https://challenge.konfhub.com/.

azure dev challenge by konfhub
Azure Dev Challenge

I learnt serverless Azure Functions, CosmosDB and Azure DevOps through this challenge. I decided to take this learning further and implement a small application to solidify my understanding.

Introduction to Azure Functions

But first, what is Azure Functions? Let me start with what is serverless. Traditionally, you would purchase/rent a server and host your application on it and this application would consume the resources as long as the server is up and running. This is time consuming and costly as well. What if there was an alternative where you could host your application on the cloud and you would only be charged for the resources whenever your application is being used. This is the concept of serverless and is gaining a lot of popularity lately. Learn more about serverless at https://azure.microsoft.com/en-gb/solutions/serverless/.

Azure Functions is Microsoft Azure’s implementation of serverless. You can call the function only when the application is being used and hence save resources and money. This also allows the flexibility for scaling easily.

Developing a RESTful API using Azure Functions

I will be implemeting a Todo API using Azure Functions and integrate it with the SendGrid API to send mails. I will cover the SendGrid integration in another story. Let’s start!

To start off, you will also need an Azure account, you can create a free account on Azure at https://azure.microsoft.com/en-gb/free/.

We would need to install the Azure Functions extension on Visual Studio Code. You can go to the Visual Studio MarketPlace here — https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions and install the extension.

After installation, select the Azure icon on the Activity bar. You should see an Azure Functions area in the Side Bar.

vscode azure icon

Sign into your Azure account, using Sign into Azure… on the top left. Once you’re signed in, open the Command Palette on Visual Studio Code by pressing F1. Enter “create new project” and select Azure Functions: Create New Project. Create a new folder in your desired location when the prompt opens and select Select to finish. Select Javascript as the language and select HTTP Trigger in the next prompt. Enter TodoGet as the name of the function and select Function in the next prompt. This will create some default files in the folder you selected including package.json, host.json and a folder for the function called TodoGet. This folder contains the code for the actual serverless functions.

Let’s test what we have so far. Open a terminal in VSCode and enter npm install to install all the node dependencies. Ensure you have NodeJS on your machine(https://nodejs.org/) for npm to work. Once all the dependencies are installed, enter npm start to start the application. You should see an output similar to this -

npm start output

If you notice, it has provided an URL for us to check the application. Go to http://localhost:7071/api/TodoGet, you should see the output —

This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.

You can also try http://localhost:7071/api/TodoGet?name=BobRoss

Congratulations, you have setup a simple Azure Functions application locally.

So far we have created one function for getting the Todos. Before we implement the logic, let’s create function for TodoAdd as well. We can do this by opening the Command Palette (F1) on VSCode. Search and select Azure Functions: Create Function… and select HTTP Trigger. Enter TodoAdd as the function name and select Function. You should notice a new folder created in the same directory called TodoAdd. You can test out this API as well using the method mentioned above with TodoAdd as the endpoint. You should expect the same output if you have made no changes.

Application Logic

Let’s move onto the application logic. The logic for each API/function is defined under the folder(TodoGet/TodoAdd), in the file index.js . The properties of the function is defined in the function.json file for each serverless function. Let’s explore the function.json file for TodoGet and make the necessary changes. You will see a bindings array with 2 objects for in and out. The in defines the properties for the incoming request. We want the incoming request to be a GET request for TodoGet. Edit the methods array to contain just the get method. We can also customise the endpoint by defining a parameter called route under the in object. For example — "route": "todo" . Add this to the function.json under the in object. Your function.json should look something like when you’re done -

Similarly, let’s change the function.json under TodoAdd as well. Remove “get” under “methods” and add the “route” parameter as “todo”.

Database Setup

To keep this application simple, let us use a sqlite database. We can use any database like CosmosDB, MySQL, Postgres and so on. I will cover implementation with CosmosDB in another article. Sqlite databases use SQL for interacting with the data and is just a single file. You can download and install sqlite3 from their official page. Once installed, in the root directory of the application, open the terminal and run -

sqlite3 database.db

This will create a database file and open the sqlite3 shell. Type the following commands in the sqlite3 shell to create a table called todos for our application.

CREATE TABLE todos(id INTEGER PRIMARY KEY AUTOINCREMENT, todo varchar(100), completed int(1));

This table can store the name of the todo and its status of completion along with an uniquely identifying ID. Verify this using .tables and .schema todos .

Type .quit to exit out of the sqlite3 shell.

Create a database service

Let’s create a service script to interact with the database. We will also need an npm package to interact with sqlite. To install this, type the following command in the root directory of the application -

npm install sqlite3

Create a new directory called Service and a new file called TodoService.js . This file will contain the code to fetch the data from the database and add data to the database. Enter the following code in TodoService.js

Now, let’s go back to index.js of TodoGet and make the changes to get the todos from this service.

First, let’s import the service into our serverless function using -

const dbService = require('../Service/TodoService');

The list of all the todos can be fetched using -

const result = await dbService.getAllTodos();

Our code should look like this after the changes are done -

Let’s make the same changes with TodoAdd as well. Here the only change would be reading the todo to be added from the request body using

const todo = req.body;

The final version of index.js under TodoAdd should look like -

Test the application

Finally, let’s run the application using npm start and test our changes.

  1. To test the GET request, we can either use the browser or Postman. Enter the url provided upon startup http://localhost:7071/api/todo . Initially this might be an empty array. Let’s test this after adding a few todos.
  2. To test the POST request, use an API client like Postman to send the request. I’m going to be using Postman.
POST request using Postman

Set the Body to raw JSON in Postman and the URL to http://localhost:7071/api/todo. Enter the todo in the following format -

{    "name": "Take Azure Dev challenge",    "completed": 1}

Hit send and you should see a Status of 200 OK in Postman.

Status 200 for POST request

Go back and try the GET request to check the inserted todo.

Tada! 🎉You have successfully implemented a serverless API. Although this is running locally, it is a serverless application using Azure Functions. The next step would be to deploy this application on Azure. I will cover that in a different article. Thank you for reading and have a great day/night. Here’s a link to the entire code on GitHub — https://github.com/avinashupadhya99/todo-azure-functions

--

--

No responses yet