Azure Functions Documentation

HTTP Trigger Bindings

HTTP trigger bindings allow your Azure Functions to be invoked via HTTP requests. This is a fundamental building block for creating serverless APIs, webhooks, and other web-enabled applications with Azure Functions.

When an HTTP request matches the configured route and authorization level, the function runtime executes your function code.

How it Works

The HTTP trigger works by defining an endpoint that Azure Functions will listen to. When a request arrives at this endpoint:

  1. The function runtime checks if the request's HTTP method and path match the trigger configuration.
  2. If the authorization level permits, the function is executed.
  3. The incoming HTTP request details (headers, body, query parameters, route parameters) are passed to your function code as an HttpRequest object.
  4. Your function code processes the request and can return an HttpResponse object, which will be sent back to the client as the response.
Note: The HTTP trigger is the default trigger when creating a new Function App in the Azure portal without specifying a trigger type.

Configuration

The HTTP trigger binding is configured in your function's function.json file (or via attributes in code for languages like C#).

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

HTTP Methods

You can specify which HTTP methods your function should respond to using the methods property. If omitted, it defaults to accepting get and post.

"methods": [ "get", "post", "put", "delete" ]

Route Template

The route property defines the URL path for your HTTP endpoint. You can use route parameters enclosed in curly braces (e.g., {itemId}) which are then accessible within your function.

Example:

  • "route": "api/users" will match /api/users.
  • "route": "api/products/{productId}" will match /api/products/123, and productId will be 123.
  • If route is omitted, the default route is the function's directory name.

Auth Level

The authLevel property controls access to your HTTP-triggered function. Supported values are:

  • anonymous: No API key required. Anyone can call the function.
  • function: A function-specific API key is required. This is the default.
  • admin: An admin API key is required. This offers the highest level of protection.
  • system: (Preview) For use with Azure API Management policies.
When using function or admin, your function URL will include a query parameter for the API key (e.g., ?code=YOUR_API_KEY).

Request and Response Objects

The HTTP trigger binding provides two core objects to your function:

  • Request (req in function.json): Represents the incoming HTTP request. It provides access to:
    • req.method: The HTTP method (e.g., "GET", "POST").
    • req.headers: Request headers.
    • req.query: Query string parameters.
    • req.params: Route parameters (if defined in the route template).
    • req.body: The request body (parsed as JSON if the content type is appropriate).
    • req.url: The full URL of the request.
  • Response (res in function.json): Used to construct and send the HTTP response back to the client. Common methods include:
    • res.send(body): Sends a response with a default status code of 200 OK.
    • res.status(statusCode).send(body): Sends a response with a specified status code.
    • res.json(body): Sends a JSON response with the Content-Type header set to application/json.
    • res.headers['Content-Type'] = 'text/plain';: Manually set response headers.

Examples

Here are examples demonstrating how to use the HTTP trigger in different languages.

C# Example

Using C# with the .NET SDK, attributes simplify the binding configuration.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

public static class HttpTriggerExample
{
    [FunctionName("HttpTriggerCSharp")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "greet/{name?}")] HttpRequest req,
        string name,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string personName = name ?? req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = System.Text.Json.JsonSerializer.Deserialize<dynamic>(requestBody);
        personName = data?.name ?? personName;

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

        return new OkObjectResult(responseMessage);
    }
}

JavaScript Example

Using Node.js with 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. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        status: 200,
        body: responseMessage
    };
};

Python Example

Using Python.

import logging
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(
             f"Hello, {name}!",
             status_code=200
        )
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

Advanced Topics

HTTP Status Codes

It's crucial to return appropriate HTTP status codes to indicate the outcome of the request. You can set the status code using the response object.

Code Description Example Usage
200 OK Successful request. res.status(200).send("Success");
201 Created Resource successfully created. res.status(201).send("Resource created");
400 Bad Request The request could not be understood or was invalid. res.status(400).send("Invalid input");
401 Unauthorized Authentication is required and has failed or has not yet been provided. res.status(401).send("Unauthorized");
404 Not Found The requested resource could not be found. res.status(404).send("Resource not found");
500 Internal Server Error A generic error message. res.status(500).send("Server error");

Binding Data

In addition to the request object, you can define other input and output bindings in your function.json. For example, you might want to bind to a Cosmos DB collection to read or write data.

The HTTP trigger itself provides the req input and res output bindings. Other bindings are configured separately.