-->

30/04/2021

Azure Functions Basics - Part 1

Azure Function: Azure Functions is a serverless application platform. It allows developers to host business logic that can be executed without provisioning infrastructure. Functions provides intrinsic scalability and you are charged only for the resources used. You can write your function code in the language of your choice, including C#, F#, JavaScript, Python, and PowerShell Core. Support for package managers like NuGet and NPM is also included, so you can use popular libraries in your business logic.

Says Microsoft, now we will build some simple stuff shown below and understand basics while we do so.


Azure function is a peice of code exceuted by events called triggers. They are meant for short period exceutions and designed to reduce complexity of your business logic.

This triggers may be a http call (or) a timely repetetion (or) a new item added in a CosmosDB (or) a new message added to a Azure Queue storage (or) a new item uploaded to a blob storage. There are wide variety of triggers avilable, which we see going ahaead.

But, you should ask a question, "Why Azure function instead of an App Service?"

App service is used to host both web applications and APIs. So why dont we deploy our code in App Services?

App Services are PaaS, this means though you haven't deployed a dedicated server, App services will be hosted on bunch of servers managed by Microsoft. So you will be paying money for hosting, irrespective of the usage. Where as in Function Apps, you pay for the usage.

I am not saying Azure function is suitable for everything. 

Here are some limitations:

1. Exceution time 10 mins: Not suitable for long running or complex business processes. Use WebJobs for long running process. If your code requires mutiple re-trys or communication with external resources try app services instead.

2. Exceution Frequency: Surely more Azure Function instances will be created every 10 seconds up to total 200 instances and each instance support many concurrent requests. Azure Functions are meant for short and on-demand calls. So if you have a functionality that should run 24/7 , better choose either App service or a service hosted on your dedictaed VM instance.  

Step 1: Go to azure portal and serach for Function Apps.

Azure Function App is a container/wrapper for a set of functions.

Create a Function App. I choose Resource group as "SampleRG", Function Name as "PurchaseOrderDemo" and Language as "Node.JS".

Please note that a storageaccount will be created as part of this. We will use it in later steps.

Lets create a new function. You can go to "Functions" option on left pane and click it.

Add a new function using "+Add" button on top.

You will be presented with a bunch of triggers. For our first function, choose "Http Trigger".

Once you select trigger, you can name the function and select authorization. 


If you select "Fucntion" as authorization, you need a key to invoke this function, which i will show in next step. Go ahead and create the function. Once the function is created , you will be taken to a page like this.


"Code+Test" is where you will write your code and do unit testing.


"Integration" is visual tool where we will add new inputs like reading data from other components like Queues and CosmosDB. 

By default the function will be created with some sample code which we can exceute and see.

Lets see how it goes.




First understand the code. All it does is accept a Http request and fetch the "name" key-value pair from its body and write a response saying Hello to the name value we provided. 

There will be 2 files associated to the function. 

"Index.js" file will have all our code. 

"function.json" file will have binding information. This code will be geneated from the triggers and inputs we configure in "Integration" part. You see more when we configure inputs for CosmosDB and Azure Queues.

Now click on that "Get Function URL" button and paste it in a new tab. It will be something like this.

Look at the highlighted part in URL, this is what you copied from the "Get Function URL" button. There is a code embeded there due to the fact we choose "Function" as authorization earlier. If you choose "Anonymous" as authorization, you need no code to invoke this function via http call.

I have added "&name=PRATAP" at the end, this is the body of the http call i passed as query string.

Thus by making a http call i invoked the function, and it responded to me by reading my name from the call.

This is what out of the box functionality does.

Step 2: Time to create a Cosmos db and containers for our purchase order data .  A database account is required to create DB. 


 Once DB account it created you will be taken to a page, on the left pannel click "Data Explorer" option. It will be empty. 

Lets create the Cosmos DB now. If you click the arrow next to "+New Container" , you can see "+New Database" option. Select it.


Once the DB is created, this is how Data Explorer will look like.


Now select "New Container" option. A cointainer is collection of Items. I choose "/id" as partition key.


Once container is created, lets test it by adding a item manually.


Remeber Cosmos DB is a NoSQL database designed to store non sturctured data like json. 

Click on "New Item" button and enter our first data item record, and click "Save" button.

BOOM... new item information has been saved to Cosmos DB. Lets modify our "Fn_Save_PurchaseOrder" function to do the same, when it was invoked with right data.

Step 3: Open the function we have created and tested earlier "Fn_Save_PurchaseOrder".

Click on "Integration" from left menu. A visual flow will be displayed showing the triggers , inputs and outputs. We created this function to be a Http trigger, so that out mobile app can send a http call to trigger save operation. 

Saving the purchase order information to CosmosDB should be the output of this function.

Click on the "+ Add Output" button and select "CosmosDB" and give the DB name, Collection name.

 Now look at the "Document parameter name" field. The value we give in this field is registered in "function.json" file.

Now look at "Cosmos DB account name connection" field. Intially it will be empty. By clicking "New" button, you get to select the database account with which this DB is connected to. 


Click "OK" and save it. Earlier i talked about "function.json" file. The code inside holds all the refrences to triggers and inouts and outputs. This is how it looks right now.


Now select index.js file and paste below code.

module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

//creating a JSON string from request data
var newitem=JSON.stringify({
"id": req.body.id,
"item":req.body.item,
"make":req.body.make,
"model":req.body.model,
"buyer":req.body.buyer,
"address":req.body.address
});

//saving the new item to newpurchaseorder output,
//which is PurchaseOrders container in this case
context.bindings.newpurchaseorder=newitem;

//confirming the save success
context.res={
status:200,
body : "Purchase Order saved sucesfully.",
headers: {
'Content-Type': 'application/json'
}
}
}

Now save "Index.js" file. Click "Test/Run" button to unti test our code.

Use below code in the body for unti testing.

{
"id": "1002",
"item":"mobile",
"make":"samsung",
"model":"S21",
"buyer":"Pratap",
"address":"Wellington,NZ"
}
Select the post method and run the test.

Lets check the data in CosmosDB as well.

There it is. Data saved to DB sucessfully.

Now looking at the design again, we should ask why do we need second Azure function to confirm deliveries. Cant we just add that code in this function.

Answer: What if there is an exception generated in confirmation part, How do we handle it?
Azure functions are good at doing one thing "DOING ONE THING". 

In this design we add a message to a Azure Queue, which will trigger another function, which checks avilability of items and create items in Ordershipments. 

Lets say if the items are not available, then we add one more queue followed by another function which add the order details in Pending Orders container. 

Usually people say there is no re-try capability in Azure functions, but by adding error handling and Azure Queues, we can even implement re-try functionality as well.     
 In the next article we will continue adding remining functionality which familiarizes us with hadling Azure Queues and both input and Output bindings of Azure Functions.

Hope i made it as simple as possible. Part-2 link is here.

No comments:

Post a Comment