03. Build Your First Azure Functions App
Nitya Narasimhan, Ph.D
Posted on September 6, 2022
✨✨Register for the Cloud Skills Challenge! ✨✨
Skill up by completing learn modules and competing with your peers for a spot on the leaderboard. You've got till Sep 30 to get it done! 🎯
Welcome to Day 3
of #30DaysOfServerless!
Yesterday we learned core concepts and terminology for Azure Functions, the signature Functions-as-a-Service option on Azure. Today we take our first steps into building and deploying an Azure Functions app, and validate local development setup.
Ready? Let's go.
What We'll Cover
- Review the Azure Functions Developer Guide
- Build your first Function App with VS Code
- Develop locally using Azure Functions Core Tools
- Review Local Testing & Development guidelines
- Check out the Durable Functions Quickstart
- Exercise : Take the Cloud Skills Challenge!
- Resources : #30DaysOfServerless Collection.
Developer Guidance
Before we jump into development, let's familiarize ourselves with language-specific guidance from the Azure Functions Developer Guide. We'll review the JavaScript version here but guides for F#, Java, Python, C# and PowerShell are available in the docs.
A function is defined by two things: code (written in a supported programming language) and configuration (specified in a
functions.json
file, declaring the triggers, bindings and other context for execution).A function app is the unit of deployment for your functions, and is associated with a single execution context or runtime. It can contain multiple functions, but they must be in the same language.
A host configuration is runtime-specific configuration that affects all functions running in a given function app instance. It is defined in a
host.json
file.A recommended folder structure is defined for the function app, but may vary based on the programming language used. Check the documentation on folder structures to learn the default for your preferred language.
Here's an example of the JavaScript folder structure for a function app containing two functions with some shared dependencies. Note that host.json
(runtime configuration) is defined once, in the root directory. And function.json
is defined separately for each function.
FunctionsProject
| - MyFirstFunction
| | - index.js
| | - function.json
| - MySecondFunction
| | - index.js
| | - function.json
| - SharedCode
| | - myFirstHelperFunction.js
| | - mySecondHelperFunction.js
| - node_modules
| - host.json
| - package.json
| - local.settings.json
We'll dive into what the contents of these files look like, when we build and deploy the first function.
My First Function App
The documentation provides quickstart options for all supported languages. We'll walk through the JavaScript versions in this article. You have two options for development:
- using Visual Studio Code for an IDE-driven experience
- using Azure CLI for a commandline-driven experience.
I'm a huge fan of VS Code - so I'll be working through that tutorial today.
🎉 PRE-REQUISITES
- Have an Azure account with active subscription) | Create one for free
- Install Azure Functions Core Tools | Verify it's version 4.x
- Install Azure Functions VS Code Extension | Currently v 1.7.4
- Install Node.js v16 or v18 (preview) | Manage versions with NVM
Don't forget to validate your setup by checking the versions of installed software.
Install VSCode Extension
Installing the Visual Studio Code extension should automatically open this page in your IDE with similar quickstart instructions, but potentially more recent screenshots.
Note that it may make sense to install the Azure tools for Visual Studio Code extensions pack if you plan on working through the many projects in Serverless September. This includes the Azure Functions extension by default.
Create First Function App
Walk through the Create local [project] steps of the quickstart. The process is quick and painless and scaffolds out this folder structure and files. Note the existence (and locations) of functions.json
and host.json
files.
Explore the Code
Check out the functions.json
configuration file. It shows that the function is activated by an httpTrigger
with an input binding (tied to req
payload) and an output binding (tied to res
payload). And it supports both GET and POST requests on the exposed URL.
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
Check out index.js
- the function implementation. We see it logs a message to the console when invoked. It then extracts a name
value from the input payload (req) and crafts a different responseMessage
based on the presence/absence of a valid name. It returns this response in the output payload (res).
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
}
Preview Function App Locally
You can now run this function app locally using Azure Functions Core Tools. VS Code integrates seamlessly with this CLI-based tool, making it possible for you to exploit all its capabilities without leaving the IDE. In fact, the workflow will even prompt you to install those tools if they didn't already exist in your local dev environment.
Now run the function app locally by clicking on the "Run and Debug" icon in the activity bar (highlighted, left) and pressing the "▶️" (Attach to Node Functions
) to start execution. On success, your console output should show something like this.
You can test the function locally by visiting the Function Url shown (http://localhost:7071/api/HttpTrigger1
) or by opening the Workspace region of the Azure extension, and selecting the Execute Function now
menu item as shown.
In the latter case, the Enter request body
popup will show a pre-populated request of {"name":"Azure"}
that you can submit.
On successful execution, your VS Code window will show a notification as follows. Take note of the console output - it shows the message encoded in index.js
.
You can also visit the deployed function URL directly in a local browser - testing the case for a request made with no name
payload attached. Note how the response in the browser now shows the non-personalized version of the message!
🎉 Congratulations - you created and ran a function app locally!
(Re)Deploy to Azure
Now, just follow the creating a function app in Azure steps to deploy it to Azure, using an active subscription! The deployed app resource should now show up under the Function App
Resources where you can click Execute Function Now
to test the Azure-deployed version instead. You can also look up the function URL in the portal and visit that link in your local browser to trigger the function without the name context.
🎉 Congratulations - you have an Azure hosted serverless function app!
Challenge yourself and try to change the code and redeploy to Azure to return something different. You have effectively created a serverless API endpoint!
About Core Tools
That was a lot to cover! In the next few days we'll have more examples for Azure Functions app development - focused on different programming languages. So let's wrap today's post by reviewing two helpful resources.
First, let's talk about Azure Functions Core Tools - the command-line tool that lets you develop, manage, and deploy, Azure Functions projects from your local development environment. It is used transparently by the VS Code extension - but you can use it directly from a terminal for a powerful command-line end-to-end developer experience! The Core Tools commands are organized into the following contexts:
-
func
- commands to create and run functions locally -
func azure
- work with resource slike Azure Functions and Azure Storage -
func durable
- work with Durable Functions -
func extensions
- manage extensions (default nuget.org) -
func kubernetes
- work with Kubernetes and Azure Functions -
func settings
- manage environment settings for local Functions host -
func templates
- list available templates
Learn how to work with Azure Functions Core Tools.
About Local Testing
You might have noticed that the scaffold also produced a local.settings.json
file. What is that and why is it useful? By definition, the local.settings.json file "stores app settings and settings used by local development tools. Settings in the local.settings.json file are used only when you're running your project locally."
Read the guidance on Code and test Azure Functions Locally to learn more about how to configure development environments locally, for your preferred programming language, to support testing and debugging on the local Functions runtime.
Exercise
We made it! Now it's your turn!! Here are a few things you can try to apply what you learned and reinforce your understanding:
- Walk through this quickstart on your own!
- Then try the Durable Functions Quickstart as a stretch goal!
- And take the Cloud Skills Challenge to skill up in fun ways.
Resources
Bookmark and visit the #30DaysOfServerless Collection. It's the one-stop collection of resources we will keep updated with links to relevant documentation and learning resources.
Posted on September 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.