HTTP Trigger

Learn how to create and configure HTTP-triggered functions in Azure Functions.

An HTTP-triggered function is a type of Azure Function that runs in response to an HTTP request. This is a common pattern for building web APIs, webhooks, and microservices.

Key Concepts

Creating an HTTP Trigger

You can create an HTTP-triggered function using the Azure portal, Azure CLI, or by using your preferred development tools like Visual Studio Code or Visual Studio.

Using Azure CLI

To create a new HTTP-triggered function using the Azure CLI, you can use the following command:


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

This command creates a new function project (if one doesn't exist) and adds an HTTP-triggered function named MyHttpTrigger.

Function Code Example (C#)

Here's a basic example of an HTTP-triggered function in C#:


using System.IO;
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 Company.Function
{
    public static class HttpTriggerCSharp
    {
        [FunctionName("HttpTriggerCSharp")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "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);
        }
    }
}
        

Function Code Example (JavaScript)

Here's a basic example of an HTTP-triggered function in JavaScript:


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

Trigger Configuration

The HTTP trigger is configured using attributes (in C#) or in the function.json file (for other languages). The key properties include:

Example function.json


{
  "scriptFile": "../run.js",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ],
      "route": "myapi/{paramName}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
        

Handling Request Data

You can access various parts of the incoming HTTP request:

Returning Responses

The function's return value or the context.res object (JavaScript) defines the HTTP response.

Security Considerations

Always use an appropriate authLevel. For public APIs, consider using API Management or other robust authentication mechanisms in addition to Azure Functions' built-in options.

Next Steps

Explore Azure Functions Bindings to integrate with other Azure services and simplify your code.