Azure Functions Documentation

Create Your First Azure Functions Code

This guide will walk you through the process of creating and deploying your very first Azure Function. We'll cover setting up your development environment and writing basic function code.

Prerequisites: Ensure you have the Azure Functions Core Tools installed and an Azure subscription. If you don't have them, follow the local development setup guide.

Step 1: Create a New Function Project

Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command:

func init MyFunctionProject --worker-runtime dotnet --language csharp

This command initializes a new project named MyFunctionProject using the .NET runtime and C# language. You can choose other runtimes like node for JavaScript/TypeScript, python, or powershell.

Step 2: Create Your First Function

Navigate into your project directory:

cd MyFunctionProject

Now, create a new HTTP-triggered function:

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

This command creates a new function named HttpTriggerFunction with a template for an HTTP trigger. You'll be prompted to choose an authorization level. For this example, choose Anonymous.

Step 3: Explore the Generated Code

Your project structure will now include a folder for your new function:

MyFunctionProject/
├── HttpTriggerFunction/
│   ├── __init__.py   (for Python) or HttpTriggerFunction.cs (for C#)
│   └── function.json
├── host.json
├── local.settings.json
└── requirements.txt (for Python) or .csproj (for C#)

Open the function's code file (e.g., HttpTriggerFunction/HttpTriggerFunction.cs for C#) to see the generated code.

C# Example (HttpTriggerFunction.cs):


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 MyFunctionApp
{
    public static class HttpTriggerFunction
    {
        [FunctionName("HttpTriggerFunction")]
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "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;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}! This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}
                

JavaScript Example (HttpTriggerFunction/index.js):


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

Step 4: Run Your Function Locally

From the root of your project directory, start the Azure Functions host:

func start

The host will output the local URL for your HTTP-triggered function. It will typically look like this:

Http Functions:

    HttpTriggerFunction: http://localhost:7071/api/HttpTriggerFunction

Step 5: Test Your Function

Open your web browser or use a tool like curl to access the URL provided. You can test it by:

  • Without a name: Visit http://localhost:7071/api/HttpTriggerFunction.
  • With a name in the query string: Visit http://localhost:7071/api/HttpTriggerFunction?name=AzureUser.
  • With a name in the request body (using POST): Use curl:
    curl -X POST -H "Content-Type: application/json" -d '{"name": "World"}' http://localhost:7071/api/HttpTriggerFunction

You should see the personalized response from your function.

Next Steps

Congratulations on creating your first Azure Function! Here are some resources to help you continue your journey: