Microsoft Azure Documentation

HTTP Trigger (PowerShell)

This document describes how to configure and use the HTTP trigger for Azure Functions written in PowerShell.

Overview

The HTTP trigger allows your Azure Function to be invoked via an HTTP request. It's a fundamental building block for creating serverless APIs, webhooks, and microservices.

Configuration

To configure an HTTP trigger, you define it in your function's function.json file.

function.json example


{
  "scriptFile": "__init__.ps1",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
            

Key properties:

PowerShell Script (__init__.ps1)

The PowerShell script receives the HTTP request as the $req object and must return an HTTP response via the $res object.

Basic Example


param($req)

# Get query parameters
$name = $req.Query.name

# Get request body
$body = $req.Body | ConvertFrom-Json

if ($name) {
    $responseMessage = "Hello, $name"
} elseif ($body -and $body.name) {
    $responseMessage = "Hello, $($body.name)"
} else {
    $responseMessage = "Hello, World!"
}

# Create the HTTP response
$res = @{
    StatusCode = 200
    Body = $responseMessage
}

# Return the response object
return $res
            

Accessing Request Details

The $req object provides access to various parts of the HTTP request:

Creating the Response

The $res hashtable should contain the following properties:

Example with JSON Response


param($req)

$data = @{
    message = "Processing complete"
    timestamp = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")
}

$res = @{
    StatusCode = 200
    Headers = @{ 'Content-Type' = 'application/json' }
    Body = $data | ConvertTo-Json
}

return $res
            

Security and Authorization

The authLevel property in function.json is crucial for securing your HTTP-triggered functions. When set to function, you'll need to include a function key in your request URL or headers.

Example URL with function key:


https://.azurewebsites.net/api/MyHttpFunction?code=
            

Troubleshooting

Note: For more advanced scenarios, consider using bindings for request body parsing or other complex data transformations.