Quickstart: Create a function in Azure that responds to HTTP requests

In this article, you use command-line tools to create a C# class library-based function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

In this article, you use command-line tools to create a JavaScript function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

In this article, you use command-line tools to create a TypeScript function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

In this article, you use command-line tools to create a PowerShell function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

In this article, you use command-line tools to create a Python function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

In this article, you use command-line tools to create a Java function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

There is also a Visual Studio Code-based version of this article.

Note

If Maven is not your prefered development tool, check out our similar tutorials for Java developers using Gradle, IntelliJ IDEA and Visual Studio Code.

Configure your local environment

Before you begin, you must have the following:

  • Node.js, Active LTS and Maintenance LTS versions (8.11.1 and 10.14.1 recommended).

Important

The JAVA_HOME environment variable must be set to the install location of the JDK to complete this quickstart.

Prerequisite check

  • In a terminal or command window, run func --version to check that the Azure Functions Core Tools are version 2.7.1846 or later.

  • Run az --version to check that the Azure CLI version is 2.0.76 or later.

  • Run az login to sign in to Azure and verify an active subscription.

  • Run python --version (Linux/MacOS) or py --version (Windows) to check your Python version reports 3.8.x, 3.7.x or 3.6.x.

Create and activate a virtual environment

In a suitable folder, run the following commands to create and activate a virtual environment named .venv. Be sure to use Python 3.8, 3.7 or 3.6, which are supported by Azure Functions.

python -m venv .venv
source .venv/bin/activate

If Python didn't install the venv package on your Linux distribution, run the following command:

sudo apt-get install python3-venv

You run all subsequent commands in this activated virtual environment. (To exit the virtual environment, run deactivate.)

Create a local function project

In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations. In this section, you create a function project that contains a single function.

Run the func init command, as follows, to create a functions project in a folder named LocalFunctionProj with the specified runtime:

func init LocalFunctionProj --python
func init LocalFunctionProj --dotnet
func init LocalFunctionProj --javascript
func init LocalFunctionProj --typescript
func init LocalFunctionProj --powershell

In an empty folder, run the following command to generate the Functions project from a Maven archetype.

mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype 

Maven asks you for values needed to finish generating the project on deployment.
Provide the following values when prompted:

Prompt Value Description
groupId com.fabrikam A value that uniquely identifies your project across all projects, following the package naming rules for Java.
artifactId fabrikam-functions A value that is the name of the jar, without a version number.
version 1.0-SNAPSHOT Choose the default value.
package com.fabrikam A value that is the Java package for the generated function code. Use the default.

Type Y or press Enter to confirm.

Maven creates the project files in a new folder with a name of artifactId, which in this example is fabrikam-functions.

Navigate into the project folder:

cd LocalFunctionProj
cd fabrikam-functions

This folder contains various files for the project, including configurations files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

Add a function to your project by using the following command, where the --name argument is the unique name of your function (HttpExample) and the --template argument specifies the function's trigger (HTTP).

func new --name HttpExample --template "HTTP trigger"

func new creates a HttpExample.cs code file.

func new creates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json.

(Optional) Examine the file contents

If desired, you can skip to Run the function locally and examine the file contents later.

HttpExample.cs

HttpExample.cs contains a Run method that receives request data in the req variable is an HttpRequest that's decorated with the HttpTriggerAttribute, which defines the trigger behavior.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace LocalFunctionProj
{
    public static class HttpExample
    {
        [FunctionName("HttpExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}

The return object is an ActionResult that returns an response message as either an OkObjectResult (200) or a BadRequestObjectResult (400). To learn more, see Azure Functions HTTP triggers and bindings.

Function.java

Function.java contains a run method that receives request data in the request variable is an HttpRequestMessage that's decorated with the HttpTrigger annotation, which defines the trigger behavior.

/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.functions;

import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;

import java.util.Optional;

/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {
    /**
     * This function listens at endpoint "/api/HttpExample". Two ways to invoke it using "curl" command in bash:
     * 1. curl -d "HTTP Body" {your host}/api/HttpExample
     * 2. curl "{your host}/api/HttpExample?name=HTTP%20Query"
     */
    @FunctionName("HttpExample")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET, HttpMethod.POST},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        // Parse query parameter
        final String query = request.getQueryParameters().get("name");
        final String name = request.getBody().orElse(query);

        if (name == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
        } else {
            return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        }
    }
}

The response message is generated by the HttpResponseMessage.Builder API.

pom.xml

Settings for the Azure resources created to host your app are defined in the configuration element of the plugin with a groupId of com.microsoft.azure in the generated pom.xml file. For example, the configuration element below instructs a Maven-based deployment to create a function app in the java-functions-group resource group in the westus region. The function app itself runs on Windows hosted in the java-functions-app-service-plan plan, which by default is a serverless Consumption plan.

<plugin>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-functions-maven-plugin</artifactId>
    <version>${azure.functions.maven.plugin.version}</version>
    <configuration>
        <!-- function app name -->
        <appName>${functionAppName}</appName>
        <!-- function app resource group -->
        <resourceGroup>${functionResourceGroup}</resourceGroup>
        <!-- function app service plan name -->
        <appServicePlanName>java-functions-app-service-plan</appServicePlanName>
        <!-- function app region-->
        <!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-regions for all valid values -->
        <region>${functionAppRegion}</region>
        <!-- function pricingTier, default to be consumption if not specified -->
        <!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-pricing-tiers for all valid values -->
        <!-- <pricingTier></pricingTier> -->
        <runtime>
            <!-- runtime os, could be windows, linux or docker-->
            <os>windows</os>
            <!-- for docker function, please set the following parameters -->
            <!-- <image>[hub-user/]repo-name[:tag]</image> -->
            <!-- <serverId></serverId> -->
            <!-- <registryUrl></registryUrl>  -->
        </runtime>
        <appSettings>
            <property>
                <name>FUNCTIONS_EXTENSION_VERSION</name>
                <value>~3</value>
            </property>
        </appSettings>
    </configuration>
    <executions>
        <execution>
            <id>package-functions</id>
            <goals>
                <goal>package</goal>
            </goals>
        </execution>
    </executions>
</plugin>

You can change these settings to control how resources are created in Azure, such as by changing runtime.os from windows to linux before initial deployment. For a complete list of settings supported by the Maven plug-in, see the configuration details.

FunctionTest.java

The archetype also generates a unit test for your function. When you change your function to add bindings or add new functions to the project, you'll also need to modify the tests in the FunctionTest.java file.

__init__.py

__init__.py contains a main() Python function that's triggered according to the configuration in function.json.

import logging

import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

For an HTTP trigger, the function receives request data in the variable req as defined in function.json. req is an instance of the azure.functions.HttpRequest class. The return object, defined as $return in function.json, is an instance of azure.functions.HttpResponse class. To learn more, see Azure Functions HTTP triggers and bindings.

index.js

index.js exports a function that's triggered according to the configuration in function.json.

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
    };
}

For an HTTP trigger, the function receives request data in the variable req as defined in function.json. The return object, defined as $return in function.json, is the response. To learn more, see Azure Functions HTTP triggers and bindings.

index.ts

index.ts exports a function that's triggered according to the configuration in function.json.

import { AzureFunction, Context, HttpRequest } from "@azure/functions"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    context.log('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
    };

};

export default httpTrigger;

For an HTTP trigger, the function receives request data in the variable req of type HttpRequest as defined in function.json. The return object, defined as $return in function.json, is the response.

run.ps1

run.ps1 defines a function script that's triggered according to the configuration in function.json.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
    $name = $Request.Body.Name
}

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

if ($name) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})

For an HTTP trigger, the function receives request data passed to the $Request param defined in function.json. The return object, defined as Response in function.json, is passed to the Push-OutputBinding cmdlet as the response.

function.json

function.json is a configuration file that defines the input and output bindings for the function, including the trigger type.

You can change scriptFile to invoke a different Python file if desired.

{
    "scriptFile": "__init__.py",
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "http",
            "direction": "out",
            "name": "$return"
        }
    ]
}
{
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    }
  ]
}

Each binding requires a direction, a type, and a unique name. The HTTP trigger has an input binding of type httpTrigger and output binding of type http.

Run the function locally

Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

func host start
npm install
npm start
mvn clean package 
mvn azure-functions:run

Toward the end of the output, the following lines should appear:

...

Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.

Http Functions:

        HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
...

Note

If HttpExample doesn't appear as shown below, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

Copy the URL of your HttpExample function from this output to a browser and append the query string ?name=<your-name>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. The browser should display a message like Hello Functions:

Result of the function run locally in the browser

The terminal in which you started your project also shows log output as you make requests.

When you're ready, use Ctrl+C and choose y to stop the functions host.

Create supporting Azure resources for your function

Before you can deploy your function code to Azure, you need to create three resources:

  • A resource group, which is a logical container for related resources.
  • A Storage account, which maintains state and other information about your projects.
  • A function app, which provides the environment for executing your function code. A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

Use the following Azure CLI commands to create these items. Each command provides JSON output upon completion.

If you haven't done so already, sign in to Azure with the az login command:

az login

Create a resource group with the az group create command. The following example creates a resource group named AzureFunctionsQuickstart-rg in the westeurope region. (You generally create your resource group and resources in a region near you, using an available region from the az account list-locations command.)

az group create --name AzureFunctionsQuickstart-rg --location westeurope

Note

You can't host Linux and Windows apps in the same resource group. If you have an existing resource group named AzureFunctionsQuickstart-rg with a Windows function app or web app, you must use a different resource group.

Create a general-purpose storage account in your resource group and region by using the az storage account create command. In the following example, replace <STORAGE_NAME> with a globally unique name appropriate to you. Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS specifies a general-purpose account, which is supported by Functions.

az storage account create --name <STORAGE_NAME> --location westeurope --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS

The storage account incurs only a few cents (USD) for this quickstart.

Create the function app using the az functionapp create command. In the following example, replace <STORAGE_NAME> with the name of the account you used in the previous step, and replace <APP_NAME> with a globally unique name appropriate to you. The <APP_NAME> is also the default DNS domain for the function app.

If you are using Python 3.8, change --runtime-version to 3.8 and --functions_version to 3.

If you are using Python 3.6, change --runtime-version to 3.6.

az functionapp create --resource-group AzureFunctionsQuickstart-rg --os-type Linux --consumption-plan-location westeurope --runtime python --runtime-version 3.7 --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>

If you are using Node.js 8, also change --runtime-version to 8.

az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime node --runtime-version 10 --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime dotnet --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime powershell --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>

This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. The command also provisions an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. For more information, see Monitor Azure Functions. The instance incurs no costs until you activate it.

Deploy the function project to Azure

Before you use Core Tools to deploy your project to Azure, you create a production-ready build of JavaScript files from the TypeScript source files.

The following command prepares your TypeScript project for deployment:

npm run build:production 

With the necessary resources in place, you're now ready to deploy your local functions project to the function app in Azure by using the func azure functionapp publish command. In the following example, replace <APP_NAME> with the name of your app.

func azure functionapp publish <APP_NAME>

If you see the error, "Can't find app with name ...", wait a few seconds and try again, as Azure may not have fully initialized the app after the previous az functionapp create command.

The publish command shows results similar to the following output (truncated for simplicity):

...

Getting site publishing info...
Creating archive for current directory...
Performing remote build for functions project.

...

Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
        Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample?code=KYHrydo4GFe9y0000000qRgRJ8NdLFKpkakGJQfC3izYVidzzDN4gQ==

Deploy the function project to Azure

A function app and related resources are created in Azure when you first deploy your functions project. Settings for the Azure resources created to host your app are defined in the pom.xml file. In this article, you'll accept the defaults.

Tip

To create a function app running on Linux instead of Windows, change the runtime.os element in the pom.xml file from windows to linux. Running Linux in a consumption plan is supported in these regions. You can't have apps that run on Linux and apps that run on Windows in the same resource group.

Before you can deploy, use the az login Azure CLI command to sign in to your Azure subscription.

az login

Use the following command to deploy your project to a new function app.

mvn azure-functions:deploy

This creates the following resources in Azure:

  • Resource group. Named as java-functions-group.
  • Storage account. Required by Functions. The name is generated randomly based on Storage account name requirements.
  • Hosting plan. Serverless hosting for your function app in the westus region. The name is java-functions-app-service-plan.
  • Function app. A function app is the deployment and execution unit for your functions. The name is randomly generated based on your your artifactId, appended with a randomly generated number.

The deployment packages the project files and deploys them to the new function app using zip deployment. The code runs from the deployment package in Azure.

Invoke the function on Azure

Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl. In both instances, the code URL parameter is your unique function key that authorizes the invocation of your function endpoint.

Copy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter &name=Functions. The browser should display similar output as when you ran the function locally.

The output of the function run on Azure in a browser

Tip

To view near real-time logs for a published function app, use the Application Insights Live Metrics Stream.

Clean up resources

If you continue to the next step, Add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.

Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

az group delete --name AzureFunctionsQuickstart-rg
az group delete --name java-functions-group

Next steps