A RetroSearch Logo

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

Search Query:

Showing content from https://learn.microsoft.com/azure/azure-functions/create-first-function-azure-developer-cli below:

Create functions in Azure using the Azure Developer CLI

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 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
py -m venv .venv
source .venv/scripts/activate
py -m venv .venv
.venv\scripts\activate
Run in your local environment
  1. Run this command from your app folder in a terminal or command prompt:

    mvn clean package
    mvn azure-functions:run
    

    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}!")
[Function("httppost")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
    [FromBody] Person person)
{
    _logger.LogInformation($"C# HTTP POST trigger function processed a request for url {req.Body}");

    if (string.IsNullOrEmpty(person.Name) | string.IsNullOrEmpty(person.Age.ToString()) | person.Age == 0)
    {
        _logger.LogInformation("C# HTTP POST trigger function processed a request with no name/age provided.");
        return new BadRequestObjectResult("Please provide both name and age in the request body.");
    }

    var returnValue = $"Hello, {person.Name}! You are {person.Age} years old.";
    
    _logger.LogInformation($"C# HTTP POST trigger function processed a request for {person.Name} who is {person.Age} years old.");
    return new OkObjectResult(returnValue);
}
@FunctionName("httppost")
public HttpResponseMessage runPost(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.POST},
            authLevel = AuthorizationLevel.FUNCTION)
            HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a POST request.");

    // Parse request body
    String name;
    Integer age;
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(request.getBody().orElse("{}"));
        name = Optional.ofNullable(jsonNode.get("name")).map(JsonNode::asText).orElse(null);
        age = Optional.ofNullable(jsonNode.get("age")).map(JsonNode::asInt).orElse(null);
        if (name == null || age == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                    .body("Please provide both name and age in the request body.").build();
        }
    } catch (Exception e) {
        context.getLogger().severe("Error parsing request body: " + e.getMessage());
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                .body("Error parsing request body").build();
    }
const { app } = require('@azure/functions');

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

        try {
            const person = await request.json();
            const { name, age } = person;

            if (!name || !age) {
                return {
                    status: 400,
                    body: 'Please provide both name and age in the request body.'
                };
            }

            return {
                status: 200,
                body: `Hello, ${name}! You are ${age} years old.`
            };
        } catch (error) {
            return {
                status: 400,
                body: 'Invalid request body. Please provide a valid JSON object with name and age.'
            };
        }
    }
});
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";

interface Person {
    name: string;
    age: number;
}

function isPerson(obj: any): obj is Person {
    return typeof obj === 'object' && obj !== null && 
           typeof obj.name === 'string' && 
           typeof obj.age === 'number';
}

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

        try {
            const data: any  = await request.json();
    
            if (!isPerson(data)) {
                return {
                    status: 400,
                    body: 'Please provide both name and age in the request body.'
                };
            }

            return {
                status: 200,
                body: `Hello, ${data.name}! You are ${data.age} years old.`
            };
        } catch (error) {
            return {
                status: 400,
                body: 'Invalid request body. Please provide a valid JSON object with name and age.'
            };
        }
};

app.http('httppost', {
    methods: ['POST'],
    authLevel: 'function',
    handler: httpPostBodyFunction
});

This function.json file defines the httppost function:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": [
        "post"
      ],
      "route": "httppost"
    },
    {
      "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 the body of the request.
$name = $Request.Body.name
$age = $Request.Body.age
$status = [HttpStatusCode]::OK

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

if ( -not ($name -and $age)){
    $body = "Please provide both 'name' and 'age' in the request body."
    $status = [HttpStatusCode]::BadRequest
}
else {
    <# Action when all if and elseif conditions are false #>
    $body = "Hello, ${name}! You are ${age} years old."
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = $status
    Body = $body
})
@app.route(route="httppost", methods=["POST"])
def http_post(req: func.HttpRequest) -> func.HttpResponse:
    try:
        req_body = req.get_json()
        name = req_body.get('name')
        age = req_body.get('age')
        
        logging.info(f"Processing POST request. Name: {name}")

        if name and isinstance(name, str) and age and isinstance(age, int):
            return func.HttpResponse(f"Hello, {name}! You are {age} years old!")
        else:
            return func.HttpResponse(
                "Please provide both 'name' and 'age' in the request body.",
                status_code=400
            )
    except ValueError:
        return func.HttpResponse(
            "Invalid JSON in request body",
            status_code=400
        )

You can review the complete template project here.

You can review the complete template project here.

You can review the complete template project here.

You can review the complete template project here.

You can review the complete template project here.

You can review the complete template project here.

After you verify your functions locally, it's time to publish them to Azure.

Create Azure resources

This project is configured to use the azd provision command to create a function app in a Flex Consumption plan, along with other required Azure resources.

Note

This project includes a set of Bicep files that azd uses to create a secure deployment to a Flex consumption plan that follows best practices.

The azd up and azd deploy commands aren't currently supported for Java apps.

  1. In the root folder of the project, run this command to create the required Azure resources:

    azd provision
    

    The root folder contains the azure.yaml definition file required by azd.

    If you aren't already signed-in, you're asked to authenticate with your Azure account.

  2. When prompted, provide these required deployment parameters:

    Parameter Description Azure subscription Subscription in which your resources are created. Azure location Azure region in which to create the resource group that contains the new Azure resources. Only regions that currently support the Flex Consumption plan are shown.

    The azd provision command uses your response to these prompts with the Bicep configuration files to create and configure these required Azure resources:

    After the command completes successfully, you can deploy your project code to this new function app in Azure.

Deploy to Azure

You can use Core Tools to package your code and deploy it to Azure from the target output folder.

  1. Navigate to the app folder equivalent in the target output folder:

    cd http/target/azure-functions/contoso-functions
    

    This folder should have a host.json file, which indicates that it's the root of your compiled Java function app.

  2. Run these commands to deploy your compiled Java code project to the new function app resource in Azure using Core Tools:

    APP_NAME=$(azd env get-value AZURE_FUNCTION_NAME)
    func azure functionapp publish $APP_NAME
    
    for /f "tokens=*" %i in ('azd env get-value AZURE_FUNCTION_NAME') do set APP_NAME=%i
    func azure functionapp publish %APP_NAME% 
    

    The azd env get-value command gets your function app name from the local environment, which is required for deployment using func azure functionapp publish. After publishing completes successfully, you see links to the HTTP trigger endpoints in Azure.

Deploy to Azure

This project is configured to use the azd up command to deploy this project to a new function app in a Flex Consumption plan in Azure.

Tip

This project includes a set of Bicep files that azd uses to create a secure deployment to a Flex consumption plan that follows best practices.

  1. Run this command to have azd create the required Azure resources in Azure and deploy your code project to the new function app:

    azd up
    

    The root folder contains the azure.yaml definition file required by azd.

    If you aren't already signed-in, you're asked to authenticate with your Azure account.

  2. When prompted, provide these required deployment parameters:

    Parameter Description Azure subscription Subscription in which your resources are created. Azure location Azure region in which to create the resource group that contains the new Azure resources. Only regions that currently support the Flex Consumption plan are shown.

    The azd up command uses your response to these prompts with the Bicep configuration files to complete these deployment tasks:

    After the command completes successfully, you see links to the resources you created.

Invoke the function on Azure

You can now invoke your function endpoints in Azure by making HTTP requests to their URLs using your HTTP test tool or from the browser (for GET requests). When your functions run in Azure, access key authorization is enforced, and you must provide a function access key with your request.

You can use the Core Tools to obtain the URL endpoints of your functions running in Azure.

  1. In your local terminal or command prompt, run these commands to get the URL endpoint values:

    SET APP_NAME=(azd env get-value AZURE_FUNCTION_NAME)
    func azure functionapp list-functions $APP_NAME --show-keys
    
    for /f "tokens=*" %i in ('azd env get-value AZURE_FUNCTION_NAME') do set APP_NAME=%i
    func azure functionapp list-functions %APP_NAME% --show-keys 
    
    $APP_NAME = azd env get-value AZURE_FUNCTION_NAME
    func azure functionapp list-functions $APP_NAME --show-keys
    
    for /f "tokens=*" %i in ('azd env get-value AZURE_FUNCTION_NAME') do set APP_NAME=%i
    func azure functionapp list-functions %APP_NAME% --show-keys 
    

    The azd env get-value command gets your function app name from the local environment. Using the --show-keys option with func azure functionapp list-functions means that the returned Invoke URL: value for each endpoint includes a function-level access key.

  2. As before, use your HTTP test tool to validate these URLs in your function app running in Azure.

Redeploy your code

You can run the azd up command as many times as you need to both provision your Azure resources and deploy code updates to your function app.

Note

Deployed code files are always overwritten by the latest deployment package.

Your initial responses to azd prompts and any environment variables generated by azd are stored locally in your named environment. Use the azd env get-values command to review all of the variables in your environment that were used when creating Azure resources.

Clean up resources

When you're done working with your function app and related resources, you can use this command to delete the function app and its related resources from Azure and avoid incurring any further costs:

azd down --no-prompt

Note

The --no-prompt option instructs azd to delete your resource group without a confirmation from you.

This command doesn't affect your local code project.


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