This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
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.
The default return value for an HTTP-triggered function is:
HTTP 204 No Content
with an empty body in Functions 2.x and higherHTTP 200 OK
with an empty body in Functions 1.xTo modify the HTTP response, configure anoutput binding.
For more information about HTTP bindings, see theoverview andoutput binding reference.
Tip
If you plan to use the HTTP or WebHook bindings, plan to avoid port exhaustion that can be caused by improper instantiation ofHttpClient
. For more information, seeHow to manage connections in Azure Functions.
Important
This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to theAzure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to themigration guide.
Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.
The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see thePython developer guide.
This article supports both programming models.
A C# function can be created by using one of the following C# modes:
Microsoft.Azure.Functions.Worker.Extensions.*
namespaces.Microsoft.Azure.WebJobs.Extensions.*
namespaces.Important
Support will end for the in-process model on November 10, 2026. We highly recommend that youmigrate your apps to the isolated worker model for full support.
The code in this article defaults to .NET Core syntax, used in Functions version 2.x and higher. For information on the 1.x syntax, see the1.x functions templates.
The following example shows an HTTP trigger that returns a "hello, world" response as anIActionResult, usingASP.NET Core integration in .NET Isolated:
[Function("HttpFunction")]public IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req){ return new OkObjectResult($"Welcome to Azure Functions, {req.Query["name"]}!");}
The following example shows an HTTP trigger that returns a "hello world" response as anHttpResponseData object:
[Function(nameof(HttpFunction))]public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext){ var logger = executionContext.GetLogger(nameof(HttpFunction)); logger.LogInformation("message logged"); var response = req.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "text/plain; charset=utf-8"); response.WriteString("Welcome to .NET isolated worker !!"); return response;}
This section contains the following examples:
The following examples show the HTTP trigger binding.
This example reads a parameter, namedid
, from the query string, and uses it to build a JSON document returned to the client, with content typeapplication/json
.
@FunctionName("TriggerStringGet")public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) { // Item list context.getLogger().info("GET parameters are: " + request.getQueryParameters()); // Get named parameter String id = request.getQueryParameters().getOrDefault("id", ""); // Convert and display if (id.isEmpty()) { return request.createResponseBuilder(HttpStatus.BAD_REQUEST) .body("Document not found.") .build(); } else { // return JSON from to the client // Generate document final String name = "fake_name"; final String jsonDocument = "{\"id\":\"" + id + "\", " + "\"description\": \"" + name + "\"}"; return request.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(jsonDocument) .build(); }}
This example reads the body of a POST request, as aString
, and uses it to build a JSON document returned to the client, with content typeapplication/json
.
@FunctionName("TriggerStringPost") public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) { // Item list context.getLogger().info("Request body is: " + request.getBody().orElse("")); // Check request body if (!request.getBody().isPresent()) { return request.createResponseBuilder(HttpStatus.BAD_REQUEST) .body("Document not found.") .build(); } else { // return JSON from to the client // Generate document final String body = request.getBody().get(); final String jsonDocument = "{\"id\":\"123456\", " + "\"description\": \"" + body + "\"}"; return request.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(jsonDocument) .build(); } }
This example reads a mandatory parameter, namedid
, and an optional parametername
from the route path, and uses them to build a JSON document returned to the client, with content typeapplication/json
.
@FunctionName("TriggerStringRoute")public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS, route = "trigger/{id}/{name=EMPTY}") // name is optional and defaults to EMPTY HttpRequestMessage<Optional<String>> request, @BindingName("id") String id, @BindingName("name") String name, final ExecutionContext context) { // Item list context.getLogger().info("Route parameters are: " + id); // Convert and display if (id == null) { return request.createResponseBuilder(HttpStatus.BAD_REQUEST) .body("Document not found.") .build(); } else { // return JSON from to the client // Generate document final String jsonDocument = "{\"id\":\"" + id + "\", " + "\"description\": \"" + name + "\"}"; return request.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(jsonDocument) .build(); }}
Here's the code for theToDoItem
class, referenced in this example:
public class ToDoItem { private String id; private String description; public ToDoItem(String id, String description) { this.id = id; this.description = description; } public String getId() { return id; } public String getDescription() { return description; } @Override public String toString() { return "ToDoItem={id=" + id + ",description=" + description + "}"; }}
This example reads the body of a POST request. The request body gets automatically de-serialized into aToDoItem
object, and is returned to the client, with content typeapplication/json
. TheToDoItem
parameter is serialized by the Functions runtime as it is assigned to thebody
property of theHttpMessageResponse.Builder
class.
@FunctionName("TriggerPojoPost")public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<ToDoItem>> request, final ExecutionContext context) { // Item list context.getLogger().info("Request body is: " + request.getBody().orElse(null)); // Check request body if (!request.getBody().isPresent()) { return request.createResponseBuilder(HttpStatus.BAD_REQUEST) .body("Document not found.") .build(); } else { // return JSON from to the client // Generate document final ToDoItem body = request.getBody().get(); return request.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(body) .build(); }}
The following example shows an HTTP triggerTypeScript function. The function looks for aname
parameter either in the query string or the body of theHTTP request.
import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> { context.log(`Http function processed request for url "${request.url}"`); const name = request.query.get('name') || (await request.text()) || 'world'; return { body: `Hello, ${name}!` };}app.http('httpTrigger1', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: httpTrigger1,});
The following example shows an HTTP triggerJavaScript function. The function looks for aname
parameter either in the query string or the body of theHTTP request.
const { app } = require('@azure/functions');app.http('httpTrigger1', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: async (request, context) => { context.log(`Http function processed request for url "${request.url}"`); const name = request.query.get('name') || (await request.text()) || 'world'; return { body: `Hello, ${name}!` }; },});
The following example shows a trigger binding in afunction.json file and aPowerShell function. The function looks for aname
parameter either in the query string or the body of the HTTP request.
{ "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "Request", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "Response" } ]}
using namespace System.Net# Input bindings are passed in via param block.param($Request, $TriggerMetadata)# Write to the Azure Functions log stream.Write-Host "PowerShell HTTP trigger function processed a request."# Interact with query parameters or the body of the request.$name = $Request.Query.Nameif (-not $name) { $name = $Request.Body.Name}$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."if ($name) { $body = "Hello, $name. This HTTP triggered function executed successfully."}# Associate values to output bindings by calling 'Push-OutputBinding'.Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK Body = $body})
This example is an HTTP triggered function that usesHTTP streams to return chunked response data. You might use these capabilities to support scenarios like sending event data through a pipeline for real time visualization or detecting anomalies in large sets of data and providing instant notifications.
import timeimport azure.functions as funcfrom azurefunctions.extensions.http.fastapi import Request, StreamingResponseapp = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)def generate_sensor_data(): """Generate real-time sensor data.""" for i in range(10): # Simulate temperature and humidity readings temperature = 20 + i humidity = 50 + i yield f"data: {{'temperature': {temperature}, 'humidity': {humidity}}}\n\n" time.sleep(1)@app.route(route="stream", methods=[func.HttpMethod.GET])async def stream_sensor_data(req: Request) -> StreamingResponse: """Endpoint to stream real-time sensor data.""" return StreamingResponse(generate_sensor_data(), media_type="text/event-stream")
To learn more, including how to enable HTTP streams in your project, seeHTTP streams.
This example shows a trigger binding and a Python function that uses the binding. The function looks for aname
parameter either in the query string or the body of the HTTP request.
import azure.functions as funcimport loggingapp = func.FunctionApp()@app.function_name(name="HttpTrigger1")@app.route(route="hello", auth_level=func.AuthLevel.ANONYMOUS)def test_function(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') return func.HttpResponse( "This HTTP triggered function executed successfully.", status_code=200 )
Both theisolated worker model and thein-process model use theHttpTriggerAttribute
to define the trigger binding. C# script instead uses a function.json configuration file as described in theC# scripting guide.
Inisolated worker model function apps, theHttpTriggerAttribute
supports the following parameters:
Parameters | Description |
---|---|
AuthLevel | Determines what keys, if any, need to be present on the request in order to invoke the function. For supported values, seeAuthorization level. |
Methods | An array of the HTTP methods to which the function responds. If not specified, the function responds to all HTTP methods. Seecustomize the HTTP endpoint. |
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, seecustomize the HTTP endpoint. |
Applies only to the Python v2 programming model.
For Python v2 functions defined using a decorator, the following properties for a trigger are defined in theroute
decorator, which adds HttpTrigger and HttpOutput binding:
Property | Description |
---|---|
route | Route for the http endpoint. If None, it will be set to function name if present or user-defined python function name. |
trigger_arg_name | Argument name for HttpRequest. The default value is 'req'. |
binding_arg_name | Argument name for HttpResponse. The default value is '$return'. |
methods | A tuple of the HTTP methods to which the function responds. |
auth_level | Determines what keys, if any, need to be present on the request in order to invoke the function. |
For Python functions defined by usingfunction.json, see theConfiguration section.
In theJava functions runtime library, use theHttpTrigger annotation, which supports the following settings:
Applies only to the Python v1 programming model.
The following table explains the properties that you can set on theoptions
object passed to theapp.http()
method.
Property | Description |
---|---|
authLevel | Determines what keys, if any, need to be present on the request in order to invoke the function. For supported values, seeAuthorization level. |
methods | An array of the HTTP methods to which the function responds. If not specified, the function responds to all HTTP methods. Seecustomize the HTTP endpoint. |
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, seecustomize the HTTP endpoint. |
The following table explains the trigger configuration properties that you set in thefunction.json file, which differs by runtime version.
The following table explains the binding configuration properties that you set in thefunction.json file.
function.json property | Description |
---|---|
type | Required - must be set tohttpTrigger . |
direction | Required - must be set toin . |
name | Required - the variable name used in function code for the request or request body. |
authLevel | Determines what keys, if any, need to be present on the request in order to invoke the function. For supported values, seeAuthorization level. |
methods | An array of the HTTP methods to which the function responds. If not specified, the function responds to all HTTP methods. Seecustomize the HTTP endpoint. |
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, seecustomize the HTTP endpoint. |
This section details how to configure your HTTP trigger function binding.
TheHttpTrigger annotation should be applied to a method parameter of one of the following types:
The trigger input type is declared as one of the following types:
Type | Description |
---|---|
HttpRequest | Use of this type requires that the app is configured withASP.NET Core integration in .NET Isolated. This gives you full access to the request object and overall HttpContext. |
HttpRequestData | A projection of the request object. |
A custom type | When the body of the request is JSON, the runtime tries to parse it to set the object properties. |
When the trigger parameter is of typeHttpRequestData
orHttpRequest
, custom types can also be bound to other parameters usingMicrosoft.Azure.Functions.Worker.Http.FromBodyAttribute
. Use of this attribute requiresMicrosoft.Azure.Functions.Worker.Extensions.Http
version 3.1.0 or later. This is a different type than the similar attribute inMicrosoft.AspNetCore.Mvc
. When using ASP.NET Core integration, you need a fully qualified reference orusing
statement. This example shows how to use the attribute to get just the body contents while still having access to the fullHttpRequest
, using ASP.NET Core integration:
using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.Azure.Functions.Worker;using FromBodyAttribute = Microsoft.Azure.Functions.Worker.Http.FromBodyAttribute;namespace AspNetIntegration{ public class BodyBindingHttpTrigger { [Function(nameof(BodyBindingHttpTrigger))] public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req, [FromBody] Person person) { return new OkObjectResult(person); } } public record Person(string Name, int Age);}
By default when you create a function for an HTTP trigger, the function is addressable with a route of the form:
https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>
You can customize this route using the optionalroute
property on the HTTP trigger's input binding. You can use anyWeb API Route Constraint with your parameters.
The following function code accepts two parameterscategory
andid
in the route and writes a response using both parameters.
[Function("HttpTrigger1")]public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post",Route = "products/{category:alpha}/{id:int?}")] HttpRequestData req, string category, int? id,FunctionContext executionContext){ var logger = executionContext.GetLogger("HttpTrigger1"); logger.LogInformation("C# HTTP trigger function processed a request."); var message = String.Format($"Category: {category}, ID: {id}"); var response = req.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "text/plain; charset=utf-8"); response.WriteString(message); return response;}
Route parameters are defined using theroute
setting of theHttpTrigger
annotation. The following function code accepts two parameterscategory
andid
in the route and writes a response using both parameters.
package com.function;import java.util.*;import com.microsoft.azure.functions.annotation.*;import com.microsoft.azure.functions.*;public class HttpTriggerJava { public HttpResponseMessage<String> HttpTrigger( @HttpTrigger(name = "req", methods = {"get"}, authLevel = AuthorizationLevel.FUNCTION, route = "products/{category:alpha}/{id:int}") HttpRequestMessage<String> request, @BindingName("category") String category, @BindingName("id") int id, final ExecutionContext context) { String message = String.format("Category %s, ID: %d", category, id); return request.createResponseBuilder(HttpStatus.OK).body(message).build(); }}
As an example, the following TypeScript code defines aroute
property for an HTTP trigger with two parameters,category
andid
. The example reads the parameters from the request and returns their values in the response.
import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> { const category = request.params.category; const id = request.params.id; return { body: `Category: ${category}, ID: ${id}` };}app.http('httpTrigger1', { methods: ['GET'], authLevel: 'anonymous', route: 'products/{category:alpha}/{id:int?}', handler: httpTrigger1,});
As an example, the following JavaScript code defines aroute
property for an HTTP trigger with two parameters,category
andid
. The example reads the parameters from the request and returns their values in the response.
const { app } = require('@azure/functions');app.http('httpTrigger1', { methods: ['GET'], authLevel: 'anonymous', route: 'products/{category:alpha}/{id:int?}', handler: async (request, context) => { const category = request.params.category; const id = request.params.id; return { body: `Category: ${category}, ID: ${id}` }; },});
As an example, the following code defines aroute
property for an HTTP trigger with two parameters,category
andid
:
Route parameters declared in thefunction.json file are accessible as a property of the$Request.Params
object.
$Category = $Request.Params.category$Id = $Request.Params.id$Message = "Category:" + $Category + ", ID: " + $IdPush-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK Body = $Message})
The function execution context is exposed via a parameter declared asfunc.HttpRequest
. This instance allows a function to access data route parameters, query string values and methods that allow you to return HTTP responses.
Once defined, the route parameters are available to the function by calling theroute_params
method.
import loggingimport azure.functions as funcdef main(req: func.HttpRequest) -> func.HttpResponse: category = req.route_params.get('category') id = req.route_params.get('id') message = f"Category: {category}, ID: {id}" return func.HttpResponse(message)
Using this configuration, the function is now addressable with the following route instead of the original route.
https://<APP_NAME>.azurewebsites.net/api/products/electronics/357
This configuration allows the function code to support two parameters in the address,category andID. For more information on how route parameters are tokenized in a URL, seeRouting in ASP.NET Core.
By default, all function routes are prefixed withapi
. You can also customize or remove the prefix using theextensions.http.routePrefix
property in yourhost.json file. The following example removes theapi
route prefix by using an empty string for the prefix in thehost.json file.
{ "extensions": { "http": { "routePrefix": "" } }}
Route parameters that defined a function'sroute
pattern are available to each binding. For example, if you have a route defined as"route": "products/{id}"
then a table storage binding can use the value of the{id}
parameter in the binding configuration.
The following configuration shows how the{id}
parameter is passed to the binding'srowKey
.
import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';const tableInput = input.table({ connection: 'MyStorageConnectionAppSetting', partitionKey: 'products', tableName: 'products', rowKey: '{id}',});export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> { return { jsonBody: context.extraInputs.get(tableInput) };}app.http('httpTrigger1', { methods: ['GET'], authLevel: 'anonymous', route: 'products/{id}', extraInputs: [tableInput], handler: httpTrigger1,});
const { app, input } = require('@azure/functions');const tableInput = input.table({ connection: 'MyStorageConnectionAppSetting', partitionKey: 'products', tableName: 'products', rowKey: '{id}',});app.http('httpTrigger1', { methods: ['GET'], authLevel: 'anonymous', route: 'products/{id}', extraInputs: [tableInput], handler: async (request, context) => { return { jsonBody: context.extraInputs.get(tableInput) }; },});
{ "type": "table", "direction": "in", "name": "product", "partitionKey": "products", "tableName": "products", "rowKey": "{id}"}
When you use route parameters, aninvoke_URL_template
is automatically created for your function. Your clients can use the URL template to understand the parameters they need to pass in the URL when calling your function using its URL. Navigate to one of your HTTP-triggered functions in theAzure portal and selectGet function URL.
You can programmatically access theinvoke_URL_template
by using the Azure Resource Manager APIs forList Functions orGet Function.
You can now stream requests to and responses from your HTTP endpoint in Node.js v4 function apps. For more information, seeHTTP streams.
HTTP streams support in Python lets you accept and return data from your HTTP endpoints using FastAPI request and response APIs enabled in your functions. These APIs enable the host to process data in HTTP messages as chunks instead of having to read an entire message into memory.
HTTP streams are disabled by default. You need to enable this feature in your application settings and also update your code to use the FastAPI package. Note that when enabling HTTP streams, the function app will default to using HTTP streaming, and the original HTTP functionality will not work.
Add theazurefunctions-extensions-http-fastapi
extension package to therequirements.txt
file in the project, which should include at least these packages:
azure-functionsazurefunctions-extensions-http-fastapi
Add this code to thefunction_app.py
file in the project, which imports the FastAPI extension:
from azurefunctions.extensions.http.fastapi import Request, StreamingResponse
When you deploy to Azure, add the followingapplication setting in your function app:
"PYTHON_ENABLE_INIT_INDEXING": "1"
When running locally, you also need to add these same settings to thelocal.settings.json
project file.
After you enable the HTTP streaming feature, you can create functions that stream data over HTTP.
This example is an HTTP triggered function that receives and processes streaming data from a client in real time. It demonstrates streaming upload capabilities that can be helpful for scenarios like processing continuous data streams and handling event data from IoT devices.
import azure.functions as funcfrom azurefunctions.extensions.http.fastapi import JSONResponse, Requestapp = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)@app.route(route="streaming_upload", methods=[func.HttpMethod.POST])async def streaming_upload(req: Request) -> JSONResponse: """Handle streaming upload requests.""" # Process each chunk of data as it arrives async for chunk in req.stream(): process_data_chunk(chunk) # Once all data is received, return a JSON response indicating successful processing return JSONResponse({"status": "Data uploaded and processed successfully"})def process_data_chunk(chunk: bytes): """Process each data chunk.""" # Add custom processing logic here pass
You must use an HTTP client library to make streaming calls to a function's FastAPI endpoints. The client tool or browser you're using might not natively support streaming or could only return the first chunk of data.
You can use a client script like this to send streaming data to an HTTP endpoint:
import httpx # Be sure to add 'httpx' to 'requirements.txt'import asyncioasync def stream_generator(file_path): chunk_size = 2 * 1024 # Define your own chunk size with open(file_path, 'rb') as file: while chunk := file.read(chunk_size): yield chunk print(f"Sent chunk: {len(chunk)} bytes")async def stream_to_server(url, file_path): timeout = httpx.Timeout(60.0, connect=60.0) async with httpx.AsyncClient(timeout=timeout) as client: response = await client.post(url, content=stream_generator(file_path)) return responseasync def stream_response(response): if response.status_code == 200: async for chunk in response.aiter_raw(): print(f"Received chunk: {len(chunk)} bytes") else: print(f"Error: {response}")async def main(): print('helloworld') # Customize your streaming endpoint served from core tool in variable 'url' if different. url = 'http://localhost:7071/api/streaming_upload' file_path = r'<file path>' response = await stream_to_server(url, file_path) print(response)if __name__ == "__main__": asyncio.run(main())
Important
HTTP streams support for Python is generally available and is only supported for the Python v2 programming model.
If your function app is usingApp Service Authentication / Authorization, you can view information about authenticated clients from your code. This information is available asrequest headers injected by the platform.
You can also read this information from binding data.
Note
Access to authenticated client information is currently only available for .NET languages. It also isn't supported in version 1.x of the Functions runtime.
Information regarding authenticated clients is available as aClaimsPrincipal, which is available as part of the request context as shown in the following example:
The authenticated user is available viaHTTP Headers.
The authenticated user is available viaHTTP Headers.
The authorization level is a string value that indicates the kind ofauthorization key that's required to access the function endpoint. For an HTTP triggered function, the authorization level can be one of the following values:
Level value | Description |
---|---|
anonymous | No access key is required. |
function | A function-specific key is required to access the endpoint. |
admin | The master key is required to access the endpoint. |
When a level isn't explicitly set, authorization defaults to thefunction
level.
When a level isn't explicitly set, the default authorization depends on the version of the Node.js model:
Functions lets you use access keys to make it harder to access your function endpoints. Unless the authorization level on an HTTP triggered function is set toanonymous
, requests must include an access key in the request. For more information, seeWork with access keys in Azure Functions.
Most HTTP trigger templates require an access 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>
Function apps that run in containers use the domain of the container host. For an example HTTP endpoint hosted in Azure Container Apps, see the example inthis Container Apps hosting article.
The key can be included in a query string variable namedcode
, as mentioned earlier. It can also be included in anx-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 don't require keys. You can also require that the master key is used. You change the default authorization level by using theauthLevel
property in the binding JSON.
Note
When running functions locally, authorization is disabled regardless of the specified authorization level setting. After publishing to Azure, theauthLevel
setting in your trigger is enforced. Keys are still required when runninglocally in a container.
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 and higher.
In version 1.x, webhook templates provide another validation for webhook payloads. In version 2.x and higher, the base HTTP trigger still works and is the recommended approach for webhooks.
ThewebHookType
binding property indicates the type if webhook supported by the function, which also dictates the supported payload. The webhook type can be one of the following values:
Type value | Description |
---|---|
genericJson | A general-purpose webhook endpoint without logic for a specific provider. This setting restricts requests to only those using HTTP POST and with theapplication/json content type. |
github | The function responds toGitHub webhooks. Don't use theauthLevel property with GitHub webhooks. |
slack | The function responds toSlack webhooks. Don't use theauthLevel property with Slack webhooks. |
When setting thewebHookType
property, don't also set themethods
property on the binding.
To respond to GitHub webhooks, first create your function with an HTTP Trigger, and set thewebHookType property togithub
. Then copy its URL and API key into theAdd webhook page of your GitHub repository.
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. SeeAuthorization 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:
clientid
query string parameter, such ashttps://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?clientid=<KEY_NAME>
.x-functions-clientid
header.Passing binary and form data to a non-C# function requires that you use the appropriate content-type header. Supported content types includeoctet-stream
for binary data andmultipart types.
In non-C# functions, requests sent with the content-typeimage/jpeg
results in astring
value passed to the function. In cases like these, you can manually convert thestring
value to a byte array to access the raw binary data.
The HTTP request size and URL lengths are both limited based onsettings defined in the host. For more information, seeService limits.
If a function that uses the HTTP trigger doesn't complete within 230 seconds, theAzure Load Balancer 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, seeScale and hosting - Consumption plan.
Was this page helpful?
Was this page helpful?