Azure Functions HTTP Trigger Tutorial

Create and publish an HTTP-triggered serverless function.

Introduction

Azure Functions provide a serverless compute service that allows you to run code on-demand without explicit infrastructure management. The HTTP trigger is one of the most common ways to invoke a function, allowing it to be called via an HTTP request.

This tutorial will guide you through creating, developing, and publishing an HTTP-triggered Azure Function. We'll cover the following:

  • Setting up your development environment.
  • Creating a new Azure Function project.
  • Developing an HTTP-triggered function.
  • Testing the function locally.
  • Deploying the function to Azure.
  • Testing the deployed function.

Prerequisites

Before you begin, ensure you have the following installed:

Step 1: Create a New Azure Functions Project

We'll use Visual Studio Code to create our project.

  1. Open Visual Studio Code.
  2. Press F1 to open the Command Palette.
  3. Type Azure Functions: Create New Project... and select it.
  4. Choose a folder for your project and select Open.
  5. Select your language (e.g., C#).
  6. Select your project template. Choose HTTP trigger.
  7. Provide a function name (e.g., MyHttpTriggerFunction).
  8. Select an authorization level. For this tutorial, choose Anonymous. This allows anyone to call your function URL without a key.

This will create a new project with a default HTTP-triggered function. The main file for your function will be named MyHttpTriggerFunction.cs (or similar, based on your function name).

Step 2: Develop the HTTP Trigger Function

Open the MyHttpTriggerFunction.cs file. You'll see code that handles incoming HTTP requests. Let's modify it to accept a name in the request body or query string and return a personalized greeting.


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 YourNamespace
{
    public static class MyHttpTriggerFunction
    {
        [FunctionName("MyHttpTriggerFunction")]
        public static async Task<IActionResult> 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)
                ? "Hello, World! This HTTP triggered function executed successfully."
                : $"Hello, {name}! This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}
                

In this code:

  • The HttpTrigger attribute defines that this function is triggered by HTTP requests (both GET and POST). AuthorizationLevel.Anonymous means no API key is required.
  • The function accepts an HttpRequest object and an ILogger.
  • It checks for a name parameter in the query string or the JSON request body.
  • It constructs a personalized greeting or a default message.
  • It returns an OkObjectResult with the greeting message.

Step 3: Test the Function Locally

Azure Functions Core Tools allow you to run and debug your functions on your local machine.

  1. Open your project's root folder in Visual Studio Code.
  2. Press F5 to start debugging. The Azure Functions Core Tools will build your project and start a local runtime.
  3. Once the runtime starts, you'll see a list of your functions and their local URLs. For the HTTP trigger, it might look like:
    Http Method: GET, POST
    Url: http://localhost:7071/api/MyHttpTriggerFunction
  4. Open a web browser and navigate to the URL. Try these variations:
    • http://localhost:7071/api/MyHttpTriggerFunction
      (should show the default message)
    • http://localhost:7071/api/MyHttpTriggerFunction?name=AzureUser
      (should show "Hello, AzureUser!")
  5. You can also test with a POST request using tools like Postman or Insomnia. Send a POST request to the function URL with a JSON body like:
    {
      "name": "Developer"
    }
    The response should be "Hello, Developer!".
Note: If you encounter errors, check the output in the Visual Studio Code terminal for detailed logs.

Step 4: Deploy the Function to Azure

Now, let's deploy our function to Azure.

  1. Ensure you are logged into your Azure account in VS Code (use the Azure extension).
  2. Press F1 to open the Command Palette.
  3. Type Azure Functions: Deploy to Function App... and select it.
  4. Select the folder containing your function project.
  5. Choose Create new Function App in Azure... (if you don't have one already) or select an existing one.
  6. Provide a globally unique name for your new Function App.
  7. Select a runtime stack (e.g., .NET).
  8. Select an Azure region.
  9. VS Code will create the Function App in Azure and deploy your code. This may take a few minutes.

Once deployment is complete, you'll be prompted to view the deployment details.

Step 5: Test the Deployed Function

After deployment, you can test your function in Azure.

  1. In the Azure extension in VS Code, navigate to your Function App.
  2. Right-click on your deployed function (e.g., MyHttpTriggerFunction) and select Copy Function Url.
  3. Open a web browser and paste the URL. You'll see the default greeting.
  4. Add the query parameter ?name=YourAzureName to the URL and press Enter. You should see the personalized greeting.
The Azure Function URL will look something like: https://your-function-app-name.azurewebsites.net/api/MyHttpTriggerFunction

Conclusion

Congratulations! You have successfully created, developed, tested, and deployed an HTTP-triggered Azure Function. This is a fundamental pattern for building serverless APIs and microservices with Azure Functions.

From here, you can explore other triggers, bindings, advanced error handling, and integrate with other Azure services.

For more information, refer to the official Azure Functions documentation.