A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local below:

Develop Azure Functions locally using Core Tools

Azure Functions Core Tools lets you develop and test your functions on your local computer. When you're ready, you can also use Core Tools to deploy your code project to Azure and work with application settings.

You're viewing the C# version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

You're viewing the Java version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

You're viewing the JavaScript version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

You're viewing the PowerShell version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

You're viewing the Python version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

You're viewing the TypeScript version of this article. Make sure to select your preferred Functions programming language at the top of the article.

If you want to get started right away, complete the Core Tools quickstart article.

The recommended way to install Core Tools depends on the operating system of your local development computer.

The following steps use a Windows installer (MSI) to install Core Tools v4.x. For more information about other package-based installers, see the Core Tools readme.

Download and run the Core Tools installer, based on your version of Windows:

If you previously used Windows installer (MSI) to install Core Tools on Windows, you should uninstall the old version from Add Remove Programs before installing the latest version.

The following steps use Homebrew to install the Core Tools on macOS.

  1. Install Homebrew, if it's not already installed.

  2. Install the Core Tools package:

    brew tap azure/functions
    brew install azure-functions-core-tools@4
    # if upgrading on a machine that has 2.x or 3.x installed:
    brew link --overwrite azure-functions-core-tools@4
    

The following steps use APT to install Core Tools on your Ubuntu/Debian Linux distribution. For other Linux distributions, see the Core Tools readme.

  1. Install the Microsoft package repository GPG key, to validate package integrity:

    curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
    sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
    
  2. Set up the APT source list before doing an APT update.

    Ubuntu
    sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-$(lsb_release -cs 2>/dev/null)-prod $(lsb_release -cs 2>/dev/null) main" > /etc/apt/sources.list.d/dotnetdev.list'
    
    Debian
    sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/debian/$(lsb_release -rs 2>/dev/null | cut -d'.' -f 1)/prod $(lsb_release -cs 2>/dev/null) main" > /etc/apt/sources.list.d/dotnetdev.list'
    
  3. Check the /etc/apt/sources.list.d/dotnetdev.list file for one of the appropriate Linux version strings in the following table:

    Linux distribution Version Debian 12 bookworm Debian 11 bullseye Debian 10 buster Debian 9 stretch Ubuntu 24.04 noble Ubuntu 22.04 jammy Ubuntu 20.04 focal Ubuntu 19.04 disco Ubuntu 18.10 cosmic Ubuntu 18.04 bionic Ubuntu 17.04 zesty Ubuntu 16.04/Linux Mint 18 xenial
  4. Start the APT source update:

    sudo apt-get update
    
  5. Install the Core Tools package:

    sudo apt-get install azure-functions-core-tools-4
    

For help with version-related issues, see Core Tools versions.

Create your local project

In the terminal window or from a command prompt, run the following command to create a project in the MyProjFolder folder:

Java uses a Maven archetype to create the local project, along with your first HTTP triggered function. Rather than using func init and func new, you should instead follow the steps in the Command line quickstart.

func init MyProjFolder --worker-runtime javascript --model V4
func init MyProjFolder --worker-runtime javascript --model V3

This command creates a JavaScript project that uses the desired programming model version.

func init MyProjFolder --worker-runtime typescript --model V4
func init MyProjFolder --worker-runtime typescript --model V3

This command creates a TypeScript project that uses the desired programming model version.

func init MyProjFolder --worker-runtime powershell
func init MyProjFolder --worker-runtime python --model V2
func init MyProjFolder --worker-runtime python

This command creates a Python project that uses the desired programming model version.

When you run func init without the --worker-runtime option, you're prompted to choose your project language. To learn more about the available options for the func init command, see the func init reference.

Create a function

To add a function to your project, run the func new command using the --template option to select your trigger template. The following example creates an HTTP trigger named MyHttpTrigger:

func new --template "Http Trigger" --name MyHttpTrigger

This example creates a Queue Storage trigger named MyQueueTrigger:

func new --template "Azure Queue Storage Trigger" --name MyQueueTrigger

The following considerations apply when adding functions:

To learn more about the available options for the func new command, see the func new reference.

Add a binding to your function

Functions provides a set of service-specific input and output bindings, which make it easier for your function to connection to other Azure services without having to use the service-specific client SDKs. For more information, see Azure Functions triggers and bindings concepts.

To add an input or output binding to an existing function, you must manually update the function definition.

The following example shows the function definition after adding a Queue Storage output binding to an HTTP triggered function:

Because an HTTP triggered function also returns an HTTP response, the function returns a MultiResponse object, which represents both the HTTP and queue output.

[Function("HttpExample")]
public static MultiResponse Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
    FunctionContext executionContext)
{

This example is the definition of the MultiResponse object that includes the output binding:

public class MultiResponse
{
    [QueueOutput("outqueue",Connection = "AzureWebJobsStorage")]
    public string[] Messages { get; set; }
    public IActionResult HttpResponse { get; set; }
}

When applying that example to your own project, you might need to change HttpRequest to HttpRequestData and IActionResult to HttpResponseData, depending on if you are using ASP.NET Core integration or not.

[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, 
    [Queue("outqueue"),StorageAccount("AzureWebJobsStorage")] ICollector<string> msg, 
    ILogger log)

Messages are sent to the queue when the function completes. The way you define the output binding depends on your process model. For more information, including links to example binding code that you can refer to, see Add bindings to a function.

@FunctionName("HttpExample")
public HttpResponseMessage run(
        @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) 
        HttpRequestMessage<Optional<String>> request, 
        @QueueOutput(name = "msg", queueName = "outqueue", 
        connection = "AzureWebJobsStorage") OutputBinding<String> msg, 
        final ExecutionContext context) {

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

const { app, output } = require('@azure/functions');

const sendToQueue = output.storageQueue({
  queueName: 'outqueue',
  connection: 'AzureWebJobsStorage',
});

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

      const name = request.query.get('name') || (await request.text());
      context.log(`Name: ${name}`);

      if (name) {
        const msg = `Name passed to the function ${name}`;
        context.extraOutputs.set(sendToQueue, [msg]);
        return { body: msg };
      } else {
        context.log('Missing required data');
        return { status: 404, body: 'Missing required data' };
      }
    } catch (error) {
      context.log(`Error: ${error}`);
      return { status: 500, body: 'Internal Server Error' };
    }
  },
});
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["get", "post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

The way you define the output binding depends on the version of your Node.js model. For more information, including links to example binding code that you can refer to, see Add bindings to a function.

$outputMsg = $name
Push-OutputBinding -name msg -Value $outputMsg

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

@app.route(route="HttpExample")
@app.queue_output(arg_name="msg", queue_name="outqueue", connection="AzureWebJobsStorage")
def HttpExample(req: func.HttpRequest, msg: func.Out [func.QueueMessage]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["get", "post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

The way you define the output binding depends on the version of your Python model. For more information, including links to example binding code that you can refer to, see Add bindings to a function.

import {
  app,
  output,
  HttpRequest,
  HttpResponseInit,
  InvocationContext,
  StorageQueueOutput,
} from '@azure/functions';

const sendToQueue: StorageQueueOutput = output.storageQueue({
  queueName: 'outqueue',
  connection: 'AzureWebJobsStorage',
});

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

    const name = request.query.get('name') || (await request.text());
    context.log(`Name: ${name}`);

    if (name) {
      const msg = `Name passed to the function ${name}`;
      context.extraOutputs.set(sendToQueue, [msg]);
      return { body: msg };
    } else {
      context.log('Missing required data');
      return { status: 404, body: 'Missing required data' };
    }
  } catch (error) {
    context.log(`Error: ${error}`);
    return { status: 500, body: 'Internal Server Error' };
  }
}

app.http('HttpExample', {
  methods: ['GET', 'POST'],
  authLevel: 'anonymous',
  handler: HttpExample,
});
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["get", "post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

The way you define the output binding depends on the version of your Node.js model. For more information, including links to example binding code that you can refer to, see Add bindings to a function.

The following considerations apply when adding bindings to a function:

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

For more information, including links to example binding code that you can refer to, see Add bindings to a function.

Start the Functions runtime

Before you can run or debug the functions in your project, you need to start the Functions host from the root directory of your project. The host enables triggers for all functions in the project. Use this command to start the local runtime:

mvn clean package 
mvn azure-functions:run

This command must be run in a virtual environment.

When the Functions host starts, it outputs a list of functions in the project, including the URLs of any HTTP-triggered functions, like in this example:

Found the following functions:
Host.Functions.MyHttpTrigger

Job host started
Http Function MyHttpTrigger: http://localhost:7071/api/MyHttpTrigger

How your functions are loaded depends on your project configuration. To learn more, see Registering a function.

Keep in mind the following considerations when running your functions locally:

Run a local function

With your local Functions host (func.exe) running, you can now trigger individual functions to run and debug your function code. The way in which you execute an individual function depends on its trigger type.

Note

Examples in this topic use the cURL tool to send HTTP requests from the terminal or a command prompt. You can use a tool of your choice to send HTTP requests to the local server. The cURL tool is available by default on Linux-based systems and Windows 10 build 17063 and later. On older Windows, you must first download and install the cURL tool.

HTTP triggers are started by sending an HTTP request to the local endpoint and port as displayed in the func.exe output, which has this general format:

http://localhost:<PORT>/api/<FUNCTION_NAME>

In this URL template, <FUNCTION_NAME> is the name of the function or route and <PORT> is the local port on which func.exe is listening.

For example, this cURL command triggers the MyHttpTrigger quickstart function from a GET request with the name parameter passed in the query string:

curl --get http://localhost:7071/api/MyHttpTrigger?name=Azure%20Rocks

This example is the same function called from a POST request passing name in the request body, shown for both Bash shell and Windows command line:

curl --request POST http://localhost:7071/api/MyHttpTrigger --data '{"name":"Azure Rocks"}'
curl --request POST http://localhost:7071/api/MyHttpTrigger --data "{'name':'Azure Rocks'}"

The following considerations apply when calling HTTP endpoints locally:

There are two ways to execute non-HTTP triggers locally. First, you can connect to live Azure services, such as Azure Storage and Azure Service Bus. This directly mirrors the behavior of your function when running in Azure. When using live services, make sure to include the required named connection strings in the local settings file. You may consider using a different service connection during development than you do in production by using a different connection string in the local.settings.json file than you use in the function app settings in Azure.

Event Grid triggers require extra configuration to run locally.

You can also run a non-HTTP function locally using REST by calling a special endpoint called an administrator endpoint. Use this format to call the admin endpoint and trigger a specific non-HTTP function:

http://localhost:<PORT>/admin/functions/<FUNCTION_NAME>

In this URL template, <FUNCTION_NAME> is the name of the function or route and <PORT> is the local port on which func.exe is listening.

You can optionally pass test data to the execution in the body of the POST request. To pass test data, you must supply the data in the body of a POST request message, which has this JSON format:

{
    "input": "<TRIGGER_INPUT>"
}

The <TRIGGER_INPUT> value contains data in a format expected by the function. This cURL example is shown for both Bash shell and Windows command line:

curl --request POST -H "Content-Type:application/json" --data '{"input":"sample queue data"}' http://localhost:7071/admin/functions/QueueTrigger
curl --request POST -H "Content-Type:application/json" --data "{'input':'sample queue data'}" http://localhost:7071/admin/functions/QueueTrigger

The previous examples generate a POST request that passes a string sample queue data to a function named QueueTrigger function, which simulates data arriving in the queue and triggering the function

The following considerations apply when using the administrator endpoint for local testing:

Event Grid triggers have specific requirements to enable local testing. For more information, see Local testing with viewer web app.

Publish to Azure

The Azure Functions Core Tools supports three types of deployment:

Deployment type Command Description Project files func azure functionapp publish Deploys function project files directly to your function app using zip deployment. Azure Container Apps func azurecontainerapps deploy Deploys a containerized function app to an existing Container Apps environment. Kubernetes cluster func kubernetes deploy Deploys your Linux function app as a custom Docker container to a Kubernetes cluster.

You must have either the Azure CLI or Azure PowerShell installed locally to be able to publish to Azure from Core Tools. By default, Core Tools uses these tools to authenticate with your Azure account.

If you don't have these tools installed, you need to instead get a valid access token to use during deployment. You can present an access token using the --access-token option in the deployment commands.

Deploy project files

To publish your local code to a function app in Azure, use the func azure functionapp publish command, as in the following example:

func azure functionapp publish <FunctionAppName>

This command publishes project files from the current directory to the <FunctionAppName> as a .zip deployment package. If the project requires compilation, it's done remotely during deployment.

Java uses Maven to publish your local project to Azure instead of Core Tools. Use the following Maven command to publish your project to Azure:

mvn azure-functions:deploy

When you run this command, Azure resources are created during the initial deployment based on the settings in your pom.xml file. For more information, see Deploy the function project to Azure.

The following considerations apply to this kind of deployment:

Deploy containers

Core Tools lets you deploy your containerized function app to both managed Azure Container Apps environments and Kubernetes clusters that you manage.

Use the following func azurecontainerapps deploy command to deploy an existing container image to a Container Apps environment:

func azurecontainerapps deploy --name <APP_NAME> --environment <ENVIRONMENT_NAME> --storage-account <STORAGE_CONNECTION> --resource-group <RESOURCE_GROUP> --image-name <IMAGE_NAME> [--registry-password] [--registry-server] [--registry-username]

When you deploy to an Azure Container Apps environment, the following considerations apply:

For more information, see Azure Container Apps hosting of Azure Functions.

The following func kubernetes deploy command uses the Dockerfile to generate a container in the specified registry and deploy it to the default Kubernetes cluster.

func kubernetes deploy --name <DEPLOYMENT_NAME> --registry <REGISTRY_USERNAME> 

Azure Functions on Kubernetes using KEDA is an open-source effort that you can use free of cost. Best-effort support is provided by contributors and from the community. To learn more, see Deploying a function app to Kubernetes.

Work with app settings locally

When running in a function app in Azure, settings required by your functions are stored securely in app settings. During local development, these settings are instead added to the Values collection in the local.settings.json file. The local.settings.json file also stores settings used by local development tools.

Items in the Values collection in your project's local.settings.json file are intended to mirror items in your function app's application settings in Azure.

The following considerations apply when working with the local settings file:

Download application settings

From the project root, use the following command to download all application settings from the myfunctionapp12345 app in Azure:

func azure functionapp fetch-app-settings myfunctionapp12345

This command overwrites any existing settings in the local.settings.json file with values from Azure. When not already present, new items are added to the collection. For more information, see the func azure functionapp fetch-app-settings command.

Download a storage connection string

Core Tools also make it easy to get the connection string of any storage account to which you have access. From the project root, use the following command to download the connection string from a storage account named mystorage12345.

func azure storage fetch-connection-string mystorage12345

This command adds a setting named mystorage12345_STORAGE to the local.settings.json file, which contains the connection string for the mystorage12345 account. For more information, see the func azure storage fetch-connection-string command.

For improved security during development, consider encrypting the local.settings.json file.

Upload local settings to Azure

When you publish your project files to Azure without using the --publish-local-settings option, settings in the local.settings.json file aren't set in your function app. You can always rerun the func azure functionapp publish with the --publish-settings-only option to upload just the settings without republishing the project files.

The following example uploads just settings from the Values collection in the local.settings.json file to the function app in Azure named myfunctionapp12345:

func azure functionapp publish myfunctionapp12345 --publish-settings-only
Encrypt the local settings file

To improve security of connection strings and other valuable data in your local settings, Core Tools lets you encrypt the local.settings.json file. When this file is encrypted, the runtime automatically decrypts the settings when needed the same way it does with application setting in Azure. You can also decrypt a locally encrypted file to work with the settings.

Use the following command to encrypt the local settings file for the project:

func settings encrypt

Use the following command to decrypt an encrypted local setting, so that you can work with it:

func settings decrypt

When the settings file is encrypted and decrypted, the file's IsEncrypted setting also gets updated.

Configure binding extensions

Functions triggers and bindings are implemented as .NET extension (NuGet) packages. To be able to use a specific binding extension, that extension must be installed in the project.

This section doesn't apply to version 1.x of the Functions runtime. In version 1.x, supported bindings were included in the core product extension.

For C# class library projects, add references to the specific NuGet packages for the binding extensions required by your functions. C# script (.csx) project must use extension bundles.

Functions provides extension bundles to make is easy to work with binding extensions in your project. Extension bundles, which are versioned and defined in the host.json file, install a complete set of compatible binding extension packages for your app. Your host.json should already have extension bundles enabled. If for some reason you need to add or update the extension bundle in the host.json file, see Extension bundles.

If you must use a binding extension or an extension version not in a supported bundle, you need to manually install extensions. For such rare scenarios, see the func extensions install command.

Core Tools versions

Major versions of Azure Functions Core Tools are linked to specific major versions of the Azure Functions runtime. For example, version 4.x of Core Tools supports version 4.x of the Functions runtime. This version is the recommended major version of both the Functions runtime and Core Tools. You can determine the latest release version of Core Tools in the Azure Functions Core Tools repository.

Starting with version 4.0.6517 of the Core Tools, in-process model projects must reference version 4.5.0 or later of Microsoft.NET.Sdk.Functions. If an earlier version is used, the func start command will error.

Run the following command to determine the version of your current Core Tools installation:

func --version

Unless otherwise noted, the examples in this article are for version 4.x.

The following considerations apply to Core Tools installations:

Next steps

Learn how to develop, test, and publish Azure functions by using Azure Functions core tools. Azure Functions Core Tools is open source and hosted on GitHub. To file a bug or feature request, open a GitHub issue.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4