Azure Functions HTTP triggers and bindings

This article explains how to work with HTTP triggers and output bindings in Azure Functions.

An HTTP trigger can be customized to respond to webhooks.

This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the following resources:

Tip

If you plan to use the HTTP or WebHook bindings, plan to avoid port exhaustion that can be caused by improper instantiation of HttpClient. For more information, see How to manage connections in Azure Functions.

The code in this article defaults to Functions 2.x syntax which uses .NET Core. For information on the 1.x syntax, see the 1.x functions templates.

Packages - Functions 1.x

The HTTP bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Http NuGet package, version 1.x. Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

Support for this binding is automatically provided in all development environments. You don't have to manually install the package or register the extension.

Packages - Functions 2.x

The HTTP bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Http NuGet package, version 3.x. Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

Support for this binding is automatically provided in all development environments. You don't have to manually install the package or register the extension.

Trigger

The HTTP trigger lets you invoke a function with an HTTP request. You can use an HTTP trigger to build serverless APIs and respond to webhooks.

By default, an HTTP trigger returns HTTP 200 OK with an empty body in Functions 1.x, or HTTP 204 No Content with an empty body in Functions 2.x. To modify the response, configure an HTTP output binding.

Trigger - example

The following example shows a C# function that looks for a name parameter either in the query string or the body of the HTTP request. Notice that the return value is used for the output binding, but a return value attribute isn't required.

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

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

Trigger - attributes

In C# class libraries and Java, the HttpTrigger attribute is available to configure the function.

You can set the authorization level and allowable HTTP methods in attribute constructor parameters, webhook type, and a route template. For more information about these settings, see Trigger - configuration.

This example demonstrates how to use the HttpTrigger attribute.

[FunctionName("HttpTriggerCSharp")]
public static Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)
{
    ...
}

For a complete example, see the trigger example.

Trigger - configuration

The following table explains the binding configuration properties that you set in the function.json file and the HttpTrigger attribute.

function.json property Attribute property Description
type n/a Required - must be set to httpTrigger.
direction n/a Required - must be set to in.
name n/a Required - the variable name used in function code for the request or request body.
authLevel AuthLevel Determines what keys, if any, need to be present on the request in order to invoke the function. The authorization level can be one of the following values:
  • anonymous—No API key is required.
  • function—A function-specific API key is required. This is the default value if none is provided.
  • admin—The master key is required.
For more information, see the section about authorization keys.
methods Methods An array of the HTTP methods to which the function responds. If not specified, the function responds to all HTTP methods. See customize the http endpoint.
route Route Defines the route template, controlling to which request URLs your function responds. The default value if none is provided is <functionname>. For more information, see customize the http endpoint.
webHookType WebHookType Supported only for the version 1.x runtime.

Configures the HTTP trigger to act as a webhook receiver for the specified provider. Don't set the methods property if you set this property. The webhook type can be one of the following values:
  • genericJson—A general-purpose webhook endpoint without logic for a specific provider. This setting restricts requests to only those using HTTP POST and with the application/json content type.
  • github—The function responds to GitHub webhooks. Do not use the authLevel property with GitHub webhooks. For more information, see the GitHub webhooks section later in this article.
  • slack—The function responds to Slack webhooks. Do not use the authLevel property with Slack webhooks. For more information, see the Slack webhooks section later in this article.

Trigger - usage

The trigger input type is declared as either HttpRequest or a custom type. If you choose HttpRequest, you get full access to the request object. For a custom type, the runtime tries to parse the JSON request body to set the object properties.

Customize the HTTP endpoint

By default when you create a function for an HTTP trigger, the function is addressable with a route of the form:

http://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>

You can customize this route using the optional route property on the HTTP trigger's input binding. As an example, the following function.json file defines a route property for an HTTP trigger:

{
    "bindings": [
    {
        "type": "httpTrigger",
        "name": "req",
        "direction": "in",
        "methods": [ "get" ],
        "route": "products/{category:alpha}/{id:int?}"
    },
    {
        "type": "http",
        "name": "res",
        "direction": "out"
    }
    ]
}

Using this configuration, the function is now addressable with the following route instead of the original route.

http://<APP_NAME>.azurewebsites.net/api/products/electronics/357

This allows the function code to support two parameters in the address, category and id.

You can use any Web API Route Constraint with your parameters. The following C# function code makes use of both parameters.

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;

public static IActionResult Run(HttpRequest req, string category, int? id, ILogger log)
{
    var message = String.Format($"Category: {category}, ID: {id}");
    return (ActionResult)new OkObjectResult(message);
}

By default, all function routes are prefixed with api. You can also customize or remove the prefix using the http.routePrefix property in your host.json file. The following example removes the api route prefix by using an empty string for the prefix in the host.json file.

{
    "http": {
    "routePrefix": ""
    }
}

Working with client identities

If your function app is using App Service Authentication / Authorization, you can view information about authenticated clients from your code. This information is available as request headers injected by the platform.

You can also read this information from binding data. This capability is only available to the Functions 2.x runtime. It is also currently only available for .NET languages.

Information regarding authenticated clients is available as a ClaimsPrincipal. The ClaimsPrincipal is available as part of the request context as shown in the following example:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

public static IActionResult Run(HttpRequest req, ILogger log)
{
    ClaimsPrincipal identities = req.HttpContext.User;
    // ...
    return new OkObjectResult();
}

Alternatively, the ClaimsPrincipal can simply be included as an additional parameter in the function signature:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Newtonsoft.Json.Linq;

public static void Run(JObject input, ClaimsPrincipal principal, ILogger log)
{
    // ...
    return;
}

Authorization keys

Functions lets you use keys to make it harder to access your HTTP function endpoints during development. A standard HTTP trigger may require such an API key be present in the request.

Important

While keys may help obfuscate your HTTP endpoints during development, they are not intended as a way to secure an HTTP trigger in production. To learn more, see Secure an HTTP endpoint in production.

Note

In the Functions 1.x runtime, webhook providers may use keys to authorize requests in a variety of ways, depending on what the provider supports. This is covered in Webhooks and keys. The version 2.x runtime does not include built-in support for webhook providers.

There are two types of keys:

  • Host keys: These keys are shared by all functions within the function app. When used as an API key, these allow access to any function within the function app.
  • Function keys: These keys apply only to the specific functions under which they are defined. When used as an API key, these only allow access to that function.

Each key is named for reference, and there is a default key (named "default") at the function and host level. Function keys take precedence over host keys. When two keys are defined with the same name, the function key is always used.

Each function app also has a special master key. This key is a host key named _master, which provides administrative access to the runtime APIs. This key cannot be revoked. When you set an authorization level of admin, requests must use the master key; any other key results in authorization failure.

Caution

Due to the elevated permissions in your function app granted by the master key, you should not share this key with third parties or distribute it in native client applications. Use caution when choosing the admin authorization level.

Obtaining keys

Keys are stored as part of your function app in Azure and are encrypted at rest. To view your keys, create new ones, or roll keys to new values, navigate to one of your HTTP-triggered functions in the Azure portal and select Manage.

Manage function keys in the portal.

You may obtain function keys programmatically by using Key management APIs.

API key authorization

Most HTTP trigger templates require an API key in the request. So your HTTP request normally looks like the following URL:

https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?code=<API_KEY>

The key can be included in a query string variable named code, as above. It can also be included in an x-functions-key HTTP header. The value of the key can be any function key defined for the function, or any host key.

You can allow anonymous requests, which do not require keys. You can also require that the master key be used. You change the default authorization level by using the authLevel property in the binding JSON. For more information, see Trigger - configuration.

Note

When running functions locally, authorization is disabled regardless of the specified authentication level setting. After publishing to Azure, the authLevel setting in your trigger is enforced. Keys are still required when running locally in a container.

Secure an HTTP endpoint in production

To fully secure your function endpoints in production, you should consider implementing one of the following function app-level security options:

  • Turn on App Service Authentication / Authorization for your function app. The App Service platform lets use Azure Active Directory (AAD) and several third-party identity providers to authenticate clients. You can use this to implement custom authorization rules for your functions, and you can work with user information from your function code. To learn more, see Authentication and authorization in Azure App Service and Working with client identities.

  • Use Azure API Management (APIM) to authenticate requests. APIM provides a variety of API security options for incoming requests. To learn more, see API Management authentication policies. With APIM in place, you can configure your function app to accept requests only from the IP address of your APIM instance. To learn more, see IP address restrictions.

  • Deploy your function app to an Azure App Service Environment (ASE). ASE provides a dedicated hosting environment in which to run your functions. ASE lets you configure a single front-end gateway that you can use to authenticate all incoming requests. For more information, see Configuring a Web Application Firewall (WAF) for App Service Environment.

When using one of these function app-level security methods, you should set the HTTP-triggered function authentication level to anonymous.

Webhooks

Note

Webhook mode is only available for version 1.x of the Functions runtime. This change was made to improve the performance of HTTP triggers in version 2.x.

In version 1.x, webhook templates provide additional validation for webhook payloads. In version 2.x, the base HTTP trigger still works and is the recommended approach for webhooks.

GitHub webhooks

To respond to GitHub webhooks, first create your function with an HTTP Trigger, and set the webHookType property to github. Then copy its URL and API key into the Add webhook page of your GitHub repository.

Slack webhooks

The Slack webhook generates a token for you instead of letting you specify it, so you must configure a function-specific key with the token from Slack. See Authorization keys.

Webhooks and keys

Webhook authorization is handled by the webhook receiver component, part of the HTTP trigger, and the mechanism varies based on the webhook type. Each mechanism does rely on a key. By default, the function key named "default" is used. To use a different key, configure the webhook provider to send the key name with the request in one of the following ways:

  • Query string: The provider passes the key name in the clientid query string parameter, such as https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?clientid=<KEY_NAME>.
  • Request header: The provider passes the key name in the x-functions-clientid header.

Trigger - limits

The HTTP request length is limited to 100 MB (104,857,600 bytes), and the URL length is limited to 4 KB (4,096 bytes). These limits are specified by the httpRuntime element of the runtime's Web.config file.

If a function that uses the HTTP trigger doesn't complete within about 2.5 minutes, the gateway will time out and return an HTTP 502 error. The function will continue running but will be unable to return an HTTP response. For long-running functions, we recommend that you follow async patterns and return a location where you can ping the status of the request. For information about how long a function can run, see Scale and hosting - Consumption plan.

Output

Use the HTTP output binding to respond to the HTTP request sender. This binding requires an HTTP trigger and allows you to customize the response associated with the trigger's request. If an HTTP output binding is not provided, an HTTP trigger returns HTTP 200 OK with an empty body in Functions 1.x, or HTTP 204 No Content with an empty body in Functions 2.x.

Output - configuration

The following table explains the binding configuration properties that you set in the function.json file. For C# class libraries, there are no attribute properties that correspond to these function.json properties.

Property Description
type Must be set to http.
direction Must be set to out.
name The variable name used in function code for the response, or $return to use the return value.

Output - usage

To send an HTTP response, use the language-standard response patterns. In C# or C# script, make the function return type IActionResult or Task<IActionResult>. In C#, a return value attribute isn't required.

For example responses, see the trigger example.

host.json settings

This section describes the global configuration settings available for this binding in version 2.x. The example host.json file below contains only the version 2.x settings for this binding. For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.

Note

For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.

{
    "extensions": {
        "http": {
            "routePrefix": "api",
            "maxOutstandingRequests": 200,
            "maxConcurrentRequests": 100,
            "dynamicThrottlesEnabled": true,
            "hsts": {
                "isEnabled": true,
                "maxAge": "10"
            },
            "customHeaders": {
                "X-Content-Type-Options": "nosniff"
            }
        }
    }
}
Property Default Description
customHeaders none Allows you to set custom headers in the HTTP response. The previous example adds the X-Content-Type-Options header to the response to avoid content type sniffing.
dynamicThrottlesEnabled true* When enabled, this setting causes the request processing pipeline to periodically check system performance counters like connections/threads/processes/memory/cpu/etc. and if any of those counters are over a built-in high threshold (80%), requests will be rejected with a 429 "Too Busy" response until the counter(s) return to normal levels.
*The default in a consumption plan is true. The default in a dedicated plan is false.
hsts not enabled When isEnabled is set to true, the HTTP Strict Transport Security (HSTS) behavior of .NET Core is enforced, as defined in the HstsOptions class. The above example also sets the maxAge property to 10 days.
maxConcurrentRequests 100* The maximum number of http functions that are executed in parallel. This allows you to control concurrency, which can help manage resource utilization. For example, you might have an http function that uses a lot of system resources (memory/cpu/sockets) such that it causes issues when concurrency is too high. Or you might have a function that makes outbound requests to a third party service, and those calls need to be rate limited. In these cases, applying a throttle here can help.
*The default for a consumption plan is 100. The default for a dedicated plan is unbounded (-1).
maxOutstandingRequests 200* The maximum number of outstanding requests that are held at any given time. This limit includes requests that are queued but have not started executing, as well as any in progress executions. Any incoming requests over this limit are rejected with a 429 "Too Busy" response. That allows callers to employ time-based retry strategies, and also helps you to control maximum request latencies. This only controls queuing that occurs within the script host execution path. Other queues such as the ASP.NET request queue will still be in effect and unaffected by this setting.
*\The default for a consumption plan is 200. The default for a dedicated plan is unbounded (-1).
routePrefix api The route prefix that applies to all routes. Use an empty string to remove the default prefix.

Next steps

Learn more about Azure functions triggers and bindings