DEV Community

Cover image for 03. Build Your First Azure Functions App
Nitya Narasimhan, Ph.D for Microsoft Azure

Posted on • Originally published at azure.github.io on

03. Build Your First Azure Functions App


✨✨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


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.

  1. 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).

  2. 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.

  3. 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.

  4. 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
Enter fullscreen mode Exit fullscreen mode

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:

I'm a huge fan of VS Code - so I'll be working through that tutorial today.

πŸŽ‰ PRE-REQUISITES

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.

Visual Studio Code Extension for VS Code

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.

Final screenshot for VS Code workflow


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"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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
    };
}
Enter fullscreen mode Exit fullscreen mode

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.

Final screenshot for VS Code workflow

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.

Final screenshot for VS Code workflow

In the latter case, the Enter request body popup will show a pre-populated request of {"name":"Azure"} that you can submit.

Final screenshot for VS Code workflow

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.

Final screenshot for VS Code workflow

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!

Final screenshot for VS Code workflow

πŸŽ‰ 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:

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:


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.

Top comments (0)