Quickstart: Create a Python function in Azure from the command line

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.

This article covers both Python programming models supported by Azure Functions. Use the selector at the top to choose your programming model.

Note

The Python v2 programming model for Functions is currently in Preview. To learn more about the Python v2 programming model, see the Developer Reference Guide.

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

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

Configure your local environment

Before you begin, you must have the following requirements in place:

  • The Azurite storage emulator. While you can also use an actual Azure Storage account, the article assumes you're using this emulator.

Prerequisite check

Verify your prerequisites, which depend on whether you're using Azure CLI or Azure PowerShell for creating Azure resources.

  • In a terminal or command window, run func --version to check that the Azure Functions Core Tools version is 4.x.
  • In a terminal or command window, run func --version to check that the Azure Functions Core Tools version is 4.0.4785 or later.
  • Run az --version to check that the Azure CLI version is 2.4 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.9.x, 3.8.x, or 3.7.x.

Create and activate a virtual environment

In a suitable folder, run the following commands to create and activate a virtual environment named .venv. Make sure that you're using 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.

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.

  1. 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
    
  2. Go to the project folder.

    cd LocalFunctionProj
    

    This folder contains various files for the project, including configuration 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.

  3. 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" --authlevel "anonymous"
    

    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.

    Get the list of templates by using the following command:

    func templates list -l python
    
  1. Run the func init command as follows to create a functions project in a folder named LocalFunctionProj with the specified runtime and the specified programming model version.

    func init LocalFunctionProj --python -m V2
    
  2. Go to the project folder.

    cd LocalFunctionProj
    

    This folder contains various files for the project, including configuration 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.

  3. The file function_app.py can include all functions within your project. To start with, there's already an HTTP function stored in the file.

import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="HttpTrigger1")
@app.route(route="hello")
def test_function(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse("HttpTrigger1 function processed a request!")

(Optional) Examine the file contents

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

__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. For more information, see Azure Functions HTTP triggers and bindings.

function.json

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

If desired, you can change scriptFile to invoke a different Python file.

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

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.

function_app.py is the entry point to the function and where functions will be stored and/or referenced. This file will include configuration of triggers and bindings through decorators, and the function content itself.

For more information, see Azure Functions HTTP triggers and bindings.

Start the storage emulator

By default, local development uses the Azurite storage emulator. This emulator is used when the AzureWebJobsStorage setting in the local.settings.json project file is set to UseDevelopmentStorage=true. When using the emulator, you must start the local Azurite storage emulator before running the function.

You can skip this step if the AzureWebJobsStorage setting in local.settings.json is set to the connection string for an Azure Storage account instead of UseDevelopmentStorage=true.

Use the following command to start the Azurite storage emulator:

azurite

For more information, see Run Azurite

Run the function locally

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

    func start
    

    Toward the end of the output, the following lines must 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 above, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, go to the project's root folder, and run the previous command again.

  2. Copy the URL of your HTTP 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 response message that echoes back your query string value. The terminal in which you started your project also shows log output as you make requests.

  3. When you're done, press Ctrl + C and type 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 the 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 commands to create these items. Both Azure CLI and PowerShell are supported.

  1. If you haven't done so already, sign in to Azure.

    az login
    

    The az login command signs you into your Azure account.

  2. When you're using the Azure CLI, you can turn on the param-persist option that automatically tracks the names of your created resources. For more information, see Azure CLI persisted parameter.

    az config param-persist on
    
  3. Create a resource group named AzureFunctionsQuickstart-rg in your chosen region.

    az group create --name AzureFunctionsQuickstart-rg --location <REGION>
    

    The az group create command creates a resource group. In the above command, replace <REGION> with a region near you, using an available region code returned from the az account list-locations command.

    In the current v2 programming model preview, choose a region from one of the following locations: France Central, West Central US, North Europe, China East, East US, or North Central US.

    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.

  4. Create a general-purpose storage account in your resource group and region.

    az storage account create --name <STORAGE_NAME> --sku Standard_LRS
    

    The az storage account create command creates the storage account.

    In the previous example, replace <STORAGE_NAME> with a name that's appropriate to you and unique in Azure Storage. Names must contain 3 to 24 characters numbers and lowercase letters only. Standard_LRS specifies a general-purpose account supported by Functions.

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

  5. Create the function app in Azure.

    az functionapp create --consumption-plan-location westeurope --runtime python --runtime-version 3.9 --functions-version 4 --name <APP_NAME> --os-type linux --storage-account <STORAGE_NAME>
    

    The az functionapp create command creates the function app in Azure. If you're using Python 3.8, 3.7, or 3.6, change --runtime-version to 3.8, 3.7, or 3.6, respectively. You must supply --os-type linux because Python functions can't run on Windows, which is the default.

    In the previous example, replace <APP_NAME> with a globally unique name appropriate to you. The <APP_NAME> is also the default DNS domain for the function app.

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

After you've successfully created your function app in Azure, you're now ready to deploy your local functions project 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>

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

Update app settings

To use the Python v2 model in your function app, you need to add a new application setting in Azure named AzureWebJobsFeatureFlags with a value of EnableWorkerIndexing. This setting is already in your local.settings.json file.

Run the following command to add this setting to your new function app in Azure.

az functionapp config appsettings set --name <FUNCTION_APP_NAME> --resource-group <RESOURCE_GROUP_NAME> --settings AzureWebJobsFeatureFlags=EnableWorkerIndexing

In the previous example, replace <FUNCTION_APP_NAME> and <RESOURCE_GROUP_NAME> with the name of your function app and resource group, respectively. This setting is already in your local.settings.json file.

Verify in Azure

Run the following command to view near real-time streaming logs in Application Insights in the Azure portal.

func azure functionapp logstream <APP_NAME> --browser

In a separate terminal window or in the browser, call the remote function again. A verbose log of the function execution in Azure is shown in the terminal.

Clean up resources

If you continue to the next step and 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

Next steps

Having issues with this article?