Skip to content

HTTP API Patterns

Build HTTP APIs in PowerShell using the HttpRequestContext input and HttpResponseContext output binding.

Route and Method Configuration

function.json:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": ["get", "post"],
      "route": "orders/{id?}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    }
  ]
}

Parsing the Request

param($Request, $TriggerMetadata)

# Route parameter
$id = $Request.Params.id

# Query string
$status = $Request.Query.Status

# JSON body (already deserialized into a Hashtable/PSObject)
$payload = $Request.Body

Returning Structured Responses

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode  = [System.Net.HttpStatusCode]::OK
    Headers     = @{ "Content-Type" = "application/json" }
    Body        = @{ id = $id; status = "processed" } | ConvertTo-Json
})

Error Handling

if (-not $id) {
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [System.Net.HttpStatusCode]::BadRequest
        Body       = "Missing order id"
    })
    return
}

Always return early

After pushing an error response, return immediately to avoid pushing a second value to the same output binding.

See Also

Sources