Private/Invoke-PrismRequest.ps1

function Invoke-PrismRequest {
    <#
    .SYNOPSIS
        Internal helper that issues an authenticated request against the Nutanix
        Prism Central v4 REST API.
 
    .DESCRIPTION
        Resolves the named PrismSession, builds the fully-qualified request URI from
        the relative API path and an optional query hashtable, honors the session's
        SSL settings, attaches the session's WebSession (Basic Authorization header +
        IGW session cookie), serializes the body to JSON when needed and invokes the
        request.
 
        All public Prism wrapper functions funnel their HTTP calls through this helper
        so the session/SSL/serialization boilerplate lives in exactly one place.
        Public wrappers include the session's ApiVersion in their request paths.
 
    .PARAMETER PrismSession
        The server/FQDN of the PrismSession to use. May be omitted when only one session exists.
 
    .PARAMETER Path
        The API path relative to the '/api/' base, for example
        'vmm/v4.2/ahv/config/vms' or 'vmm/v4.2/content/ovas/{extId}'.
 
    .PARAMETER Method
        The HTTP method to use. Defaults to 'GET'.
 
    .PARAMETER Query
        A hashtable of query string parameters. Null/empty values are skipped and
        values are URL-encoded. Useful for OData parameters such as $page, $limit,
        $filter, $orderby and $select.
 
    .PARAMETER Body
        The request body. A string is sent as-is; any other object is converted to
        JSON before sending.
 
    .PARAMETER Header
        Additional request headers to merge in (for example If-Match or
        NTNX-Request-Id).
 
    .PARAMETER PassThruResponse
        Returns the full Invoke-WebRequest response object (so callers can read
        response headers such as ETag) instead of the deserialized body.
 
    .OUTPUTS
        The deserialized API response, or the full web response when -PassThruResponse
        is supplied.
    #>


    [CmdletBinding()]
    param(
        [Parameter()][string]$PrismSession,
        [Parameter(Mandatory)][string]$Path,
        [Parameter()][string]$Method = 'GET',
        [Parameter()][hashtable]$Query,
        [Parameter()]$Body,
        [Parameter()][hashtable]$Header,
        [Parameter()][switch]$PassThruResponse
    )

    ## Resolve the session (this validates / refreshes it as needed)
    $PrismSessionConfig = Get-PrismSession $PrismSession
    if (-not $PrismSessionConfig) {
        Write-Host 'PrismSession: [' -NoNewline
        Write-Host $PrismSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-PrismSession command.'
        Throw 'Prism Session Not Found. Use New-PrismSession command before using features.'
    }

    ## Ensure the session has a version; wrappers include it in their request paths.
    if ([string]::IsNullOrEmpty($PrismSessionConfig.ApiVersion)) {
        throw 'Prism session has no ApiVersion. Recreate it with New-PrismSession.'
    }
    $requestPath = $Path.TrimStart('/')

    ## Build the base URI. Prism Central APIs are served beneath '/api'.
    $uri = 'https://{0}:{1}/api/{2}' -f $PrismSessionConfig.PrismServer, $PrismSessionConfig.PrismPort, $requestPath

    ## Append any query string parameters
    if ($Query -and $Query.Count) {
        $pairs = foreach ($key in $Query.Keys) {
            $value = $Query[$key]
            if ($null -eq $value -or $value -eq '') { continue }
            '{0}={1}' -f [uri]::EscapeDataString($key), [uri]::EscapeDataString([string]$value)
        }
        if ($pairs) {
            $uri += '?' + ($pairs -join '&')
        }
    }

    $RestMethodSplat = @{
        Uri                  = $uri
        Method               = $Method
        WebSession           = $PrismSessionConfig.PrismWebSession
        TimeoutSec           = 100
        ProgressAction       = 'SilentlyContinue'
        SkipCertificateCheck = $PrismSessionConfig.AllowInsecureSSL
        # Prism Central v4 returns a non-standard, unquoted ETag. PowerShell otherwise
        # validates the If-Match header and rejects it ("not a valid quoted string"),
        # so skipping header validation lets the raw ETag pass through. Do not remove.
        SkipHeaderValidation = $true
    }

    $RequestHeaders = @{
        'Accept'       = 'application/json'
        'Content-Type' = 'application/json'
    }
    if ($Header) {
        foreach ($key in $Header.Keys) { $RequestHeaders[$key] = $Header[$key] }
    }
    $RestMethodSplat.Headers = $RequestHeaders

    if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) {
        $RestMethodSplat.Body = ($Body -is [string]) ? $Body : ($Body | ConvertTo-Json -Depth 25 -Compress)
    }

    try {
        if ($PassThruResponse.IsPresent) {
            return Invoke-WebRequest @RestMethodSplat
        }
        return Invoke-RestMethod @RestMethodSplat
    } catch {
        throw $_
    }
}