HTTP output bindings enable your Azure Functions to send HTTP responses back to the caller. This is the fundamental mechanism for creating HTTP-triggered APIs with Azure Functions.
When a function is triggered by an HTTP request, you can define an HTTP output binding that will be used to construct and send the response. This binding typically takes the form of an HttpResponseData object in your function code.
You configure HTTP output bindings in your function.json file.
function.json{
"scriptFile": "run.csx",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
In this configuration:
httpTrigger binding is for the incoming request.http binding with direction: "out" and name: "res" is the HTTP output binding. This name (res) will correspond to the parameter in your function code that you use to set the response.using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
public static class HttpExample
{
[Function("HttpExample")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestData req,
FunctionContext context)
{
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
await response.WriteStringAsync("Hello from Azure Functions!");
return response;
}
}
module.exports = async function (context, req) {
context.res = {
status: 200,
headers: {
"Content-Type": "text/plain"
},
body: "Hello from Azure Functions!"
};
};
You can easily return JSON by setting the Content-Type header and providing a JSON string or object as the response body.
JSON.stringify().
You can specify the HTTP status code for your response. The default is usually 200 OK.
var response = req.CreateResponse(HttpStatusCode.BadRequest); // Example for 400 Bad Request
response.WriteStringAsync("Invalid input provided.");
return response;
context.res = {
status: 404, // Example for 404 Not Found
body: "Resource not found."
};
Add custom headers to your HTTP response as needed.
response.Headers.Add("X-Custom-Header", "MyValue");
context.res = {
status: 200,
headers: {
"Content-Type": "application/json",
"X-Custom-Header": "MyValue"
},
body: { message: "Success" }
};
For robust API development, it's crucial to handle errors gracefully by returning appropriate error status codes and messages.