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
- Request Handling: The function receives an incoming HTTP request and can access its properties like method, headers, query parameters, and body.
- Response Generation: The function returns an HTTP response, including a status code, headers, and a response body.
- Route Configuration: You can define custom routes for your HTTP-triggered functions to manage API endpoints.
- Authentication: Azure Functions provides built-in mechanisms for securing HTTP-triggered functions.
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:
- authLevel: Determines how the function is authorized. Common values are- Anonymous,- Function, and- Admin.
- methods: An array of HTTP methods the function will respond to (e.g., "get", "post", "put", "delete").
- route: Allows you to define a custom URL route for the function, overriding the default route. If- nullor omitted, a default route is generated.
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:
- Query Parameters: Accessible via req.Query(C#) orreq.query(JavaScript).
- Request Body: Accessible via req.Body(C#, requires reading stream) orreq.body(JavaScript, usually parsed JSON).
- Headers: Accessible via req.Headers(C#) orreq.headers(JavaScript).
- Route Parameters: If defined in the route, they are accessible viareq.Queryorreq.params(JavaScript).
Returning Responses
The function's return value or the context.res object (JavaScript) defines the HTTP response.
- Status Code: Set via OkObjectResult(body)orStatusCode(int)(C#), orcontext.res.status(JavaScript).
- Headers: Set via res.Headers(C#) orcontext.res.headers(JavaScript).
- Body: Set via the return object (C#) or context.res.body(JavaScript).
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.