HTTP Trigger in TypeScript
This document provides a reference for creating and configuring HTTP-triggered functions using TypeScript with Azure Functions.
Function Signature
An HTTP-triggered function in TypeScript typically has the following signature. It receives a request object and can return a response.
import { AzureFunction, Context, HttpRequest } from "@azure/functions";
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise {
context.log('HTTP trigger function processed a request.');
// Access request data
const name = (req.query.name || (req.body && req.body.name));
const message = 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.";
// Set response
context.res = {
status: 200,
body: message
};
};
export default httpTrigger;
Request Object (HttpRequest)
The HttpRequest object provides access to details about the incoming HTTP request.
Properties
| Property | Type | Description |
|---|---|---|
method |
string |
The HTTP method (e.g., 'GET', 'POST'). |
url |
string |
The full URL of the request. |
headers |
Record<string, string | undefined> |
Request headers. |
query |
Record<string, string | undefined> |
Query string parameters. |
params |
Record<string, string> |
Route parameters extracted from the URL path. |
body |
any |
The request body. Can be a string, JSON object, etc. |
rawBody |
Buffer |
The raw request body as a Buffer. |
Context Object (Context)
The Context object provides access to runtime information and methods for interacting with the Azure Functions host.
Properties and Methods
| Property/Method | Type | Description |
|---|---|---|
log |
(message: string, ...args: any[]) => void |
Logs messages to the Azure Functions host. |
done |
(error?: any, result?: any) => void |
Signals that the function execution is complete. (Less common in async functions). |
res |
HttpResponse | undefined |
The response object to be sent back to the client. |
bindings |
Record<string, any> |
Access to other input and output bindings. |
bindingData |
Record<string, any> |
Data from bindings or trigger metadata. |
Response Object (HttpResponse)
The response object allows you to define the HTTP response sent back to the client.
Properties
| Property | Type | Description |
|---|---|---|
status |
number | string |
The HTTP status code (e.g., 200, 404). |
body |
any |
The response body. Can be a string, JSON object, or Buffer. |
headers |
Record<string, string> |
Response headers. |
isRaw |
boolean |
Indicates if the response body is raw (Buffer). |
Tip: For JSON responses, ensure your body is a JavaScript object. Azure Functions will automatically set the Content-Type header to application/json.
Routing and Function.json
The routing for HTTP-triggered functions is defined in the function.json file. For example:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
],
"route": "greet/{name?}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
In this example, the route greet/{name?} allows you to access the function via /api/greet/yourname or /api/greet. The parameter name will be available in context.bindingData.name or req.params.name.
Handling Different HTTP Methods
You can inspect req.method to handle different HTTP verbs:
if (req.method === 'POST') {
// Handle POST request logic
context.res = {
status: 201,
body: "Resource created"
};
} else if (req.method === 'GET') {
// Handle GET request logic
context.res = {
status: 200,
body: "Resource retrieved"
};
}
Accessing Request Body
If the request's Content-Type header is application/json, the Azure Functions runtime will automatically parse the body into a JavaScript object when you access req.body.
// Assuming request body is JSON: {"product": "Widget", "quantity": 5}
const product = req.body.product;
const quantity = req.body.quantity;
For other content types, req.body will be a string, or you can use req.rawBody to access the raw Buffer.
Error Handling
It's good practice to implement robust error handling:
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
try {
// ... function logic ...
context.res = { status: 200, body: "Success" };
} catch (error) {
context.log.error("An error occurred:", error);
context.res = {
status: 500,
body: "Internal Server Error"
};
}
};
Pro Tip: For complex applications, consider using libraries like Express.js within your Azure Function or explore Durable Functions for orchestrating workflows.