Azure Functions Documentation

HTTP Trigger Bindings

The HTTP trigger allows your Azure Function to be invoked via an HTTP request. It's a fundamental building block for creating serverless APIs, webhooks, and other HTTP-based services.

Key Features

  • Flexible Routing: Define custom routes and HTTP methods (GET, POST, PUT, DELETE, etc.).
  • Request & Response Handling: Easily access incoming request details (headers, query parameters, body) and construct HTTP responses.
  • Authentication: Integrates with Azure Functions' built-in authentication mechanisms.
  • Multiple Language Support: Works seamlessly with C#, JavaScript, Python, Java, PowerShell, and more.

Configuration

The HTTP trigger is configured in the function.json file. The primary property is route, which defines the URL path for your function.

Example function.json:

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

In this example:

  • authLevel: Specifies the authentication level required to invoke the function. Common values are anonymous, function, and admin.
  • methods: An array of allowed HTTP methods.
  • route: Defines the URL template. greet/{name?} means the function can be accessed at /api/greet or /api/greet/<name>. The ? makes the name parameter optional.

Input (Request)

The HTTP trigger input object (commonly named req) provides access to the incoming HTTP request.

Request Properties:

  • method: The HTTP method of the request (e.g., "GET", "POST").
  • url: The full URL of the request.
  • headers: A dictionary of request headers.
  • query: A dictionary of query string parameters.
  • params: A dictionary of route parameters (e.g., name in /api/greet/{name}).
  • body: The request body. The type depends on the Content-Type header (e.g., JSON, form data).

Output (Response)

The HTTP trigger output binding (commonly named res) is used to construct the HTTP response.

Response Properties:

  • status: The HTTP status code (e.g., 200, 404, 500).
  • body: The content of the response body. Can be a string, JSON object, etc.
  • headers: A dictionary of response headers.
  • isRaw: Set to true if the body should be sent without JSON serialization.

Handling HTTP Requests (Python Example)

Here's a typical Python function using the HTTP trigger:

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}. This HTTP triggered function executed successfully.",
             status_code=200
        )
    else:
        return func.HttpResponse(
             "Please pass a name in the query string or in the request body",
             status_code=400
        )

More Examples

Routing with Different Methods:

Configure function.json to accept only POST requests:

{
  "scriptFile": "run.csx",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

And handle it in your code (e.g., C# script):

// In run.csx
using System.Net;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;

public static class HttpPostExample
{
    [Function("HttpPostExample")]
    public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
    {
        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain");
        response.WriteString("This is a POST request response!");
        return response;
    }
}

Returning JSON:

// In 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,
        headers: {
            'Content-Type': 'application/json'
        },
        body: { message: responseMessage }
    };
};

Security Considerations

Always use appropriate authLevel settings. For public-facing APIs, consider using API Management in conjunction with Azure Functions for more advanced security features like rate limiting, IP filtering, and OAuth integration.

When using function or admin auth levels, Azure Functions generates API keys. You must include this key in the x-functions-key header of your HTTP request.

For sensitive data in request bodies, ensure your function handles it securely and avoid logging sensitive information.