Get Started With Microsoft Azure Functions and Deployment through IDE VS Code
Today we are going to start with Azure functions by creating Our First Azure Functions using Vs code.
This Article is for the absolute beginner.
What we will learn is
* What are Azure Functions?
* How to Integrate Azure Functions with VS Code.
* Create the Serverless App.
* How to run your application.
* Create Azure functions and Understand the Code.
* API endpoints.
* Routing.
* Adding CORS Policy.
* Deployment of Azure Function to Azure Portal Using VS Code.
* Azure Functions pricing and limits
What is Azure Function?
Azure Functions is a serverless compute service that runs our code on demand without hosting it on the server and managing infrastructure.
Azure Functions are serverless computing solutions hosted on and powdered by the **Microsoft Azure Public cloud platform** that allows you to write less code, Low cost and less infrastructure management.
Azure Functions make it easy to deploy your application Underlying its cloud infrastructure that provides efficient resources to keep your application up and running.
How to Integrate Azure Functions with VS Code.
First of all, we need to install the extension of **Azure Function** in VS Code.
After installation of the extension at the most left menu of the VS code you will see the Azure button for navigation of creating the Azure project and azure functions.
Create the Serverless App
* To get started with the creation of the azure project and function first we need to log our azure portal in Vs code. Click on the sign-in option as shown below.
* Select the button to create a new project in the Azure Functions explorer as shown in the above image1.
* Select a new, empty folder to create your project.
* Select your desired programming language. In our case, we will be using javascript.
* Select “HTTP trigger” for your project’s function.
* Use “give a name to your function” as you like.
* Select “**Anonymous**” for the authorization level, which enables anyone to call your function endpoint without a key. We are using **Anonymous** for the reason that we don’t want to expose our function keys for security purposes.
learn more about authorization levels.
How to run your application
This extension integrates with the Azure Functions Core Tools to let you run your project locally before publishing it to Azure.
**First Method**
Go to the “package.json” file and you will see the start script. We can start the azure function by typing the command in the terminal **func start*. Just like we do in node server architecture (npm Start).
**Second Method**
To start your project, press F5 or the “play” button. By default it will run on port 7071, so Your URL should look like this: http://localhost:7071/api/<name of your function>
Create Azure functions and Understand the Code
We created the azure function In the first step while creating the project. Your function now must look like the below. It contains 3 files
* function.json contains the configuration for a function.
* index.js have the main logic of a function like operation logic which will tell the function what to do.
* sample.dat is the test file for the function, here you will write the test script.
In the **index.js** file your function script will look like the below. This is the default generated code by azure function.
module.exports = function(context, req) {
context.log('Node.js HTTP trigger function processed a request.', req.originalUrl);
if (req.query.name || (req.body && req.body.name)) {
context.res = {
// status defaults to 200 */
body: "Hello " + (req.query.name || req.body.name) }; }
else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done(); };
Handling req and res with the context in the above script
In the above script, we can see the first argument of the function is “**context**” and the second is “**req**”. The first argument is always going to be “context”.
Instead of passing the **req** as a second argument we can also handle the “req” with the **context** as below.
module.exports = function(context) {
context.log('Node.js HTTP trigger function processed a request.', req.originalUrl);
if (context.req.query.name || (context.req.body && context.req.body.name)) {
context.res = {
// status defaults to 200 */
body: "Hello " + (req.query.name || req.body.name) };
}
else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done();
};
What is context?
**context** object is used for receiving and sending binding data, logging, and communicating with the runtime.
context.done() method
Lets the runtime know that your code has been completed. When your function uses the async function declaration, you do not need to use context.done(). The context.done callback is implicitly called. Async functions are available in Node 8 or a later version, which requires version 2.x of the Functions runtime.
If your function is not an async function, you must call context.done to inform the runtime that your function is complete. The execution times out if it is missing.
Find more about exporting the function from azure function, Bindings, Inputs, Outputs, Binding data types, Exporting the function as async [click here]
Explaining the function.json file
The following table explains the binding configuration properties that you set in the function.json file and the HttpTrigger attribute.
To find more about the azure function Click Here
API endpoints
Creation of routes is a cakewalk with azure function, unlike express Js. For creating the API endpoint we need to add a property named **methods** array, it will configure HTTP (POST, GET, DELETE, PATCH) in the function.json file as below.
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
Routing
Routing is very tranquil with an azure function. For routing, we just need to add a property named **route** shown below.
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"route": "httptrigger/httptriggerevent",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
Your final Api endpoint will be like this (http://localhost:7071/api/httptrigger/httptriggerevent).
Adding CORS Policy
Adding CORS Origin Policy is a manifest with a serverless azure function. Go to **app.settings.json** file and add the property called Host having the object name CORS as shown below. Your can also restrict it to a specific port like **localhost://4200** and so on.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node"
},
"Host" : {
"LocalHttpPort": 7085,
"CORS" : "*"
}
}
You can also change the default port of the service through the property name LocalHttpPort. Set this property to whatever port you want.
Now after adding this script we will be able to hit the endpoint from the front-end platform in the local environment but not in production. Here is the problem that arises, discussed below.
The azure function adds one more authentication security barrier to the azure function URL. By doing all the things we have done above we will be able to hit the endpoint locally but we will not be able to get the access for production endpoint, it is going to give us the 401 Unauthorize Error.
Note: This is the default behaviour of the azure function.
Solution
Now in order to solve this, we need to operate on the Azure portal. Click here to navigate to the AZURE PORTAL
- Goto your function. lets take an example here.
- Navigate to the Function App as shown below.
* Now after navigating to the function app you will see the dashboard like this.
* Click on your function and you will be navigated to your function portal. And click on the **CORS** as below.
Here what we are doing is we are allowing/authenticating the Frontend app to access the backend azure functions by adding there URL to the azure function. In this way, we will be able to access azure functions from the frontend application for the specific URL. We are not allowing all the Frontend URLs to access our function but only the ones which we want to. You can also allow all by giving the value astric “*” means for all, everyone is allowed to access.
Deployment of Azure Function to Azure Portal Using VS Code
This is the very exciting part of serverless computing that we were talking about before. The deployment part is painless and royal with Microsoft azure function, It’s literally a one-click deployment.
* Sign in to your Azure Account by clicking “Sign in to Azure…” in the Azure Functions explorer.
* If you don’t already have an Azure Account, click “Create a Free Azure Account”.
* Select the button to deploy.
It will Upload your azure functions to the Azure Portal.
Azure Functions pricing and limit
Azure Functions has no limits on payload size, deployment package size and code or dependency size. However, each Azure Functions host instance is limited to 1.5 GB of memory, and the default execution time limit is 5 minutes although, users can increase this to 10 minutes.
To check the price model of the Azure function links is below.
* https://azure.microsoft.com/en-us/pricing/details/functions/
Conclusion:
Azure provides pay-as-you-go pricing model means that users pay based on how much they consume which makes it cost-effective. Unlike serve architectures, serverless is no sweet and it’s more affordable, scalable, and time-efficient. Easy to develop and deploy code.
With serverless architectures, developers do not need to worry about purchasing, provisioning, and managing backend servers.