functions/New-ApiRequest.ps1

function New-ApiRequest {

    <#
    .SYNOPSIS
    Makes a API request.
 
    .DESCRIPTION
    Returns the API response.
 
    .PARAMETER ApiMethod
    Provide API Method GET, PUT or POST
 
    .PARAMETER ApiRequest
    See Datto RMM API swagger UI
 
    .PARAMETER ApiRequestBody
    Only used with PUT and POST request
 
    .INPUTS
    $apiUrl = The API URL
    $apiKey = The API Key
    $apiKeySecret = The API Secret Key
 
    .OUTPUTS
    API response
 
    #>

    
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet('GET','PUT','POST')]
        [string]$apiMethod,

        [Parameter(Mandatory=$True)]
        [string]$apiRequest,
    
        [Parameter(Mandatory=$False)]
        [string]$apiRequestBody
    )

    # Check API Parameters
    if (!$apiUrl -or !$apiKey -or !$apiSecretKey) {
        Write-Host "API Parameters missing, please run Set-DrmmApiParameters first!"
        return
    }

    # Define parameters for Invoke-WebRequest cmdlet
    $params = [ordered] @{
        Uri         = '{0}/api{1}' -f $apiUrl, $apiRequest
        Method      = $apiMethod
        ContentType = 'application/json'
        Headers     = @{'Authorization' = 'Bearer {0}' -f $apiAccessToken}
        UseBasicParsing = $True
    }

    # Add body to parameters if present
    If ($apiRequestBody) {$params.Add('Body',$apiRequestBody)}

    # Make request
    try 
    {
        (Invoke-WebRequest @params).Content
    }
    catch
    {
        
        $exceptionError = $_.Exception.Message
        
        switch ($exceptionError)
        {
    
            'The remote server returned an error: (429).' 
            {
                Start-Sleep -Seconds 60
            }

            'The remote server returned an error: (403) Forbidden.'
            {
                Start-Sleep -Seconds 300
            }

        }

        throw
    }
}