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.
Važno
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 the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration 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 the Python developer guide.
The Python v1 programming model requires you to define bindings in a separate function.json file in the function folder. For more information, see the Python developer guide.
This article supports both programming models.
Example
A C# function can be created by using one of the following C# modes:
Isolated worker model: Compiled C# function that runs in a worker process that's isolated from the runtime. Isolated worker process is required to support C# functions running on LTS and non-LTS versions .NET and the .NET Framework. Extensions for isolated worker process functions use Microsoft.Azure.Functions.Worker.Extensions.* namespaces.
In-process model: Compiled C# function that runs in the same process as the Functions runtime. In a variation of this model, Functions can be run using C# scripting, which is supported primarily for C# portal editing. Extensions for in-process functions use Microsoft.Azure.WebJobs.Extensions.* namespaces.
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 the 1.x functions templates.
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.
cs
[FunctionName("HttpTriggerCSharp")]
publicstaticasync 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 = String.Empty;
using (StreamReader streamReader = new StreamReader(req.Body))
{
requestBody = await streamReader.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");
}
The following examples show the HTTP trigger binding.
Read parameter from the query string
This example reads a parameter, named id, from the query string, and uses it to build a JSON document returned to the client, with content type application/json.
Java
@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 displayif (id.isEmpty()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from to the client// Generate documentfinal String name = "fake_name";
final String jsonDocument = "{\"id\":\"" + id + "\", " +
"\"description\": \"" + name + "\"}";
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(jsonDocument)
.build();
}
}
Read body from a POST request
This example reads the body of a POST request, as a String, and uses it to build a JSON document returned to the client, with content type application/json.
Java
@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 bodyif (!request.getBody().isPresent()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from to the client// Generate documentfinal 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();
}
}
Read parameter from a route
This example reads a mandatory parameter, named id, and an optional parameter name from the route path, and uses them to build a JSON document returned to the client, with content type application/json.
Java
@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 displayif (id == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from to the client// Generate documentfinal String jsonDocument = "{\"id\":\"" + id + "\", " +
"\"description\": \"" + name + "\"}";
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(jsonDocument)
.build();
}
}
Read POJO body from a POST request
Here's the code for the ToDoItem class, referenced in this example:
This example reads the body of a POST request. The request body gets automatically de-serialized into a ToDoItem object, and is returned to the client, with content type application/json. The ToDoItem parameter is serialized by the Functions runtime as it is assigned to the body property of the HttpMessageResponse.Builder class.
Java
@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 bodyif (!request.getBody().isPresent()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from to the client// Generate documentfinal ToDoItem body = request.getBody().get();
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(body)
.build();
}
}
The following example shows an HTTP trigger TypeScript function. The function looks for a name parameter either in the query string or the body of the HTTP request.
The following example shows an HTTP trigger JavaScript function. The function looks for a name parameter either in the query string or the body of the HTTP request.
The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding. The function looks for a name parameter either in the query string or the body of the HTTP request.
The configuration section explains these properties.
Here's the JavaScript code:
JavaScript
module.exports = asyncfunction(context, req) {
context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);
if (req.query.name || (req.body && req.body.name)) {
context.res = {
// status defaults to 200 */
body: "Hello " + (req.query.name || req.body.name)
};
}
else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
};
The following example shows a trigger binding in a function.json file and a PowerShell function. The function looks for a name parameter either in the query string or the body of the HTTP request.
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.Name
if (-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 uses HTTP streams to return chunked response data.
Python
import time
import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, StreamingResponse
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
defgenerate_sensor_data():"""Generate real-time sensor data."""for i in range(10):
# Simulate temperature and humidity readings
temperature = 20 + i
humidity = 50 + i
yieldf"data: {{'temperature': {temperature}, 'humidity': {humidity}}}\n\n"
time.sleep(1)
@app.route(route="stream", methods=[func.HttpMethod.GET])asyncdefstream_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, see HTTP streams.
This example shows a trigger binding and a Python function that uses the binding. The function looks for a name parameter either in the query string or the body of the HTTP request.
Python
import azure.functions as func
import logging
app = func.FunctionApp()
@app.function_name(name="HttpTrigger1")@app.route(route="hello", auth_level=func.AuthLevel.ANONYMOUS)deftest_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
)
This example shows a trigger binding and a Python function that uses the binding. The function looks for a name parameter either in the query string or the body of the HTTP request.
The configuration section explains these properties.
Here's the Python code:
Python
import logging
import azure.functions as func
defmain(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
ifnot name:
try:
req_body = req.get_json()
except ValueError:
passelse:
name = req_body.get('name')
if name:
return func.HttpResponse(f"Hello {name}!")
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
In isolated worker model function apps, the HttpTriggerAttribute 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, see Authorization level.
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
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.
In in-process functions, the HttpTriggerAttribute 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, see Authorization level.
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
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
Supported only for the version 1.x runtime.
Configures the HTTP trigger to act as a webhook receiver for the specified provider. For supported values, see WebHook type.
Decorators
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 the route 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 using function.json, see the Configuration section.
The following table explains the properties that you can set on the options object passed to the app.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, see Authorization level.
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
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.
The following table explains the binding configuration properties that you set in the function.json file.
function.json property
Description
type
Required - must be set to httpTrigger.
direction
Required - must be set to in.
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, see Authorization level.
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
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.
The following table explains the trigger configuration properties that you set in the function.json file, which differs by runtime version.
The following table explains the binding configuration properties that you set in the function.json file.
function.json property
Description
type
Required - must be set to httpTrigger.
direction
Required - must be set to in.
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, see Authorization level.
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
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.
The following table explains the binding configuration properties that you set in the function.json file.
function.json property
Description
type
Required - must be set to httpTrigger.
direction
Required - must be set to in.
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, see Authorization level.
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
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
Configures the HTTP trigger to act as a webhook receiver for the specified provider. For supported values, see WebHook type.
Usage
This section details how to configure your HTTP trigger function binding.
The HttpTrigger annotation should be applied to a method parameter of one of the following types:
Use of this type requires that the app is configured with ASP.NET Core integration in .NET Isolated. This gives you full access to the request object and overall HttpContext.
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 type HttpRequestData or HttpRequest, custom types can also be bound to other parameters using Microsoft.Azure.Functions.Worker.Http.FromBodyAttribute. Use of this attribute requires Microsoft.Azure.Functions.Worker.Extensions.Http version 3.1.0 or later. This is a different type than the similar attribute in Microsoft.AspNetCore.Mvc. When using ASP.NET Core integration, you need a fully qualified reference or using statement. This example shows how to use the attribute to get just the body contents while still having access to the full HttpRequest, using ASP.NET Core integration:
C#
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using FromBodyAttribute = Microsoft.Azure.Functions.Worker.Http.FromBodyAttribute;
namespaceAspNetIntegration
{
publicclassBodyBindingHttpTrigger
{
[Function(nameof(BodyBindingHttpTrigger))]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
[FromBody] Person person)
{
returnnew OkObjectResult(person);
}
}
publicrecordPerson(string Name, int Age);
}
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:
You can customize this route using the optional route property on the HTTP trigger's input binding. You can use any Web API Route Constraint with your parameters.
Route parameters are defined using the route setting of the HttpTrigger annotation. The following function code accepts two parameters category and id in the route and writes a response using both parameters.
As an example, the following TypeScript code defines a route property for an HTTP trigger with two parameters, category and id. The example reads the parameters from the request and returns their values in the response.
As an example, the following JavaScript code defines a route property for an HTTP trigger with two parameters, category and id. The example reads the parameters from the request and returns their values in the response.
The Functions runtime provides the request body from the context object. The following example shows how to read route parameters from context.bindingData.
JavaScript
module.exports = asyncfunction (context, req) {
var category = context.bindingData.category;
var id = context.bindingData.id;
var message = `Category: ${category}, ID: ${id}`;
context.res = {
body: message;
}
}
As an example, the following code defines a route property for an HTTP trigger with two parameters, category and id:
The function execution context is exposed via a parameter declared as func.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 the route_params method.
This configuration allows the function code to support two parameters in the address, category and ID. For more information on how route parameters are tokenized in a URL, see Routing in ASP.NET Core.
By default, all function routes are prefixed with api. You can also customize or remove the prefix using the extensions.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.
Route parameters that defined a function's route 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's rowKey.
When you use route parameters, an invoke_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 the Azure portal and select Get function URL.
You can programmatically access the invoke_URL_template by using the Azure Resource Manager APIs for List Functions or Get Function.
HTTP streams
You can now stream requests to and responses from your HTTP endpoint in Node.js v4 function apps. For more information, see HTTP streams.
HTTP 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. For more information, see HTTP streams in Python
Važno
HTTP streams support for Python is currently in preview and is only supported for the Python v2 programming model.
You can also read this information from binding data.
Napomena
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 a ClaimsPrincipal, which is available as part of the request context as shown in the following example:
The authenticated user is available via HTTP Headers.
C#
using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
publicstatic IActionResult Run(HttpRequest req, ILogger log)
{
ClaimsPrincipal identities = req.HttpContext.User;
// ...returnnew OkObjectResult();
}
Alternatively, the ClaimsPrincipal can simply be included as an extra parameter in the function signature:
C#
using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Newtonsoft.Json.Linq;
publicstaticvoidRun(JObject input, ClaimsPrincipal principal, ILogger log)
{
// ...return;
}
The authenticated user is available via HTTP Headers.
Authorization level
The authorization level is a string value that indicates the kind of authorization 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 the function 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 to anonymous, requests must include an access key in the request. For more information, see Work with access keys in Azure Functions.
Access key authorization
Most HTTP trigger templates require an access key in the request. So your HTTP request normally looks like the following URL:
The key can be included in a query string variable named code, as mentioned earlier. 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 don't require keys. You can also require that the master key is used. You change the default authorization level by using the authLevel property in the binding JSON.
Napomena
When running functions locally, authorization is disabled regardless of the specified authorization level setting. After publishing to Azure, the authLevel setting in your trigger is enforced. Keys are still required when running locally in a container.
Webhooks
Napomena
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.
WebHook type
The webHookType 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 the application/json content type.
The function responds to Slack webhooks. Don't use the authLevel property with Slack webhooks.
When setting the webHookType property, don't also set the methods property on the binding.
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.
Content types
Passing binary and form data to a non-C# function requires that you use the appropriate content-type header. Supported content types include octet-stream for binary data and multipart types.
Known issues
In non-C# functions, requests sent with the content-type image/jpeg results in a string value passed to the function. In cases like these, you can manually convert the string value to a byte array to access the raw binary data.
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 230 seconds, the Azure 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, see Scale and hosting - Consumption plan.
Pridružite se seriji susreta kako biste s kolegama programerima i stručnjacima izgradili skalabilna rješenja umjetne inteligencije temeljena na stvarnim slučajevima upotrebe.