Edit

Share via


Quickstart: Create and deploy functions to Azure Functions using the Azure Developer CLI

In this Quickstart, you use Azure Developer command-line tools to create functions that respond to HTTP requests. After testing the code locally, you deploy it to a new serverless function app you create running in a Flex Consumption plan in Azure Functions.

The project source uses the Azure Developer CLI (azd) to simplify deploying your code to Azure. This deployment follows current best practices for secure and scalable Azure Functions deployments.

By default, the Flex Consumption plan follows a pay-for-what-you-use billing model, which means to complete this quickstart incurs a small cost of a few USD cents or less in your Azure account.

Prerequisites

  • A secure HTTP test tool for sending requests with JSON payloads to your function endpoints. This article uses curl.

Initialize the project

You can use the azd init command to create a local Azure Functions code project from a template.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template functions-quickstart-dotnet-azd -e flexquickstart-dotnet
    

    This command pulls the project files from the template repository and initializes the project in the current folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Run this command to navigate to the http app folder:

    cd http
    
  3. Create a file named local.settings.json in the http folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
        }
    }
    

    This file is required when running locally.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template azure-functions-java-flex-consumption-azd -e flexquickstart-java 
    

    This command pulls the project files from the template repository and initializes the project in the current folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Run this command to navigate to the http app folder:

    cd http
    
  3. Create a file named local.settings.json in the http folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "java"
        }
    }
    

    This file is required when running locally.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template functions-quickstart-javascript-azd -e flexquickstart-js
    

    This command pulls the project files from the template repository and initializes the project in the root folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Create a file named local.settings.json in the root folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "node"
        }
    }
    

    This file is required when running locally.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template functions-quickstart-powershell-azd -e flexquickstart-ps
    

    This command pulls the project files from the template repository and initializes the project in the root folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Run this command to navigate to the src app folder:

    cd src
    
  3. Create a file named local.settings.json in the src folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "powershell",
            "FUNCTIONS_WORKER_RUNTIME_VERSION": "7.2"
        }
    }
    

    This file is required when running locally.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template functions-quickstart-typescript-azd -e flexquickstart-ts
    

    This command pulls the project files from the template repository and initializes the project in the root folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Create a file named local.settings.json in the root folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "node"
        }
    }
    

    This file is required when running locally.

  1. In your local terminal or command prompt, run this azd init command in an empty folder:

    azd init --template functions-quickstart-python-http-azd -e flexquickstart-py
    

    This command pulls the project files from the template repository and initializes the project in the root folder. The -e flag sets a name for the current environment. In azd, the environment is used to maintain a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.

  2. Create a file named local.settings.json in the root folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "python"
        }
    }
    

    This file is required when running locally.

Create and activate a virtual environment

In the root folder, run these commands to create and activate a virtual environment named .venv:

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

Run in your local environment

  1. Run this command from your app folder in a terminal or command prompt:

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

    When the Functions host starts in your local project folder, it writes the URL endpoints of your HTTP triggered functions to the terminal output.

  2. In your browser, navigate to the httpget endpoint, which should look like this URL:

    http://localhost:7071/api/httpget

  3. From a new terminal or command prompt window, run this curl command to send a POST request with a JSON payload to the httppost endpoint:

    curl -i http://localhost:7071/api/httppost -H "Content-Type: text/json" -d @testdata.json
    
    curl -i http://localhost:7071/api/httppost -H "Content-Type: text/json" -d "@src/functions/testdata.json"
    

    This command reads JSON payload data from the testdata.json project file. You can find examples of both HTTP requests in the test.http project file.

  4. When you're done, press Ctrl+C in the terminal window to stop the func.exe host process.

  1. Run deactivate to shut down the virtual environment.

Review the code (optional)

You can review the code that defines the two HTTP trigger function endpoints:

       [Function("httpget")]
       public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get")]
         HttpRequest req,
         string name)
       {
           var returnValue = string.IsNullOrEmpty(name)
               ? "Hello, World."
               : $"Hello, {name}.";

           _logger.LogInformation($"C# HTTP trigger function processed a request for {returnValue}.");

           return new OkObjectResult(returnValue);
       }
@FunctionName("httpget")
public HttpResponseMessage run(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.GET},
            authLevel = AuthorizationLevel.FUNCTION)
            HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a request.");

    // Parse query parameter
    String name = Optional.ofNullable(request.getQueryParameters().get("name")).orElse("World");

    return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
}
const { app } = require('@azure/functions');

app.http('httpget', {
    methods: ['GET'],
    authLevel: 'function',
    handler: async (request, context) => {
        context.log(`Http function processed request for url "${request.url}"`);

        const name = request.query.get('name') || await request.text() || 'world';

        return { body: `Hello, ${name}!` };
    }
});
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";

export async function httpGetFunction(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log(`Http function processed request for url "${request.url}"`);

    const name = request.query.get('name') || await request.text() || 'world';

    return { body: `Hello, ${name}!` };
};

app.http('httpget', {
    methods: ['GET'],
    authLevel: 'function',
    handler: httpGetFunction
});

This function.json file defines the httpget function:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": [
        "get"
      ],
      "route": "httpget"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    }
  ]
}

This run.ps1 file implements the function code:

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
$name = $Request.Query.name

$body = "This HTTP triggered function executed successfully. Pass a name in the query string 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
})
@app.route(route="httpget", methods=["GET"])
def http_get(req: func.HttpRequest) -> func.HttpResponse:
    name = req.params.get("name", "World")

    logging.info(f"Processing GET request. Name: {name}")

    return func.HttpResponse(f"Hello, {name}!")

You can review the complete template project here.

You can review the complete template project