Download attachment using SNOW REST API attachment table

Naresh Kumar Gn
Giga Contributor

Hi All,

I am trying to download an attachment which is there on a SNOW incident where I was able to download the incident but I am unable to open the downloaded file which I got via API. But when I download the same file using GUI I can open it.

Url I tried to used to download the file is given below,

https://<SNOWInstanceURL>/api/now/attachment?sysparm_query=table_name%3Dincident%5Etable_sys_id%3D<IncidentSysId>

Sample Script"

$IncidentNumber = "Incident#"
$admin = "admin"
$password = "admin" | ConvertTo-SecureString -AsPlainText -Force 
$Credential = New-Object pscredential -ArgumentList ($admin,$password)
$Uri = "https://devxxxxx.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1"
$IncidentResult = Invoke-RestMethod -Uri $Uri -Method Get -Credential $Credential
if($IncidentResult.result.sys_id -ne $null) {
    $IncidentAttachments = Invoke-RestMethod -Uri "https://devxxxxx.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" -Method Get -Credential $Credential
    $Results = $IncidentAttachments.result | Select file_name , download_link
    foreach($Result in $Results) {
        Invoke-RestMethod -Uri $($Result.download_link) -Method Get -Credential $Credential -OutFile C:\Temp\Demo\$($Result.file_name)
    }
}
else{
    "Incident Not Found!"
}

Regards,

Naresh

1 ACCEPTED SOLUTION

Naresh Kumar Gn
Giga Contributor

Yes, I have gone through the link but in my organization, they have added an encryption mechanism and they have blocked the download if it was not triggered internally within the snow.

View solution in original post

4 REPLIES 4

rahulpandey
Kilo Sage
Hi, To get the attachment file, you need to use below endpoint Instance url/api/now/attachment//file Please refer below document https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_AttachmentAPI-GETidFile.html

Naresh Kumar Gn
Giga Contributor

Yes, I have gone through the link but in my organization, they have added an encryption mechanism and they have blocked the download if it was not triggered internally within the snow.

Nikita9
Mega Expert

Hi Naresh,

 

Can you please explain how you are able to download attachment file using this code? I am also having a requirement where i need to download all RITMs attachments if user clicks on an API. 

 

Pls help.

 

Regards,

Nikita

Use this code to download all attachment from a RITM

param (
    $RITM,

    $DownloadLocation,

    $snowurl,

    $fileextenstion,
   
    $snowUser,

    $snowPass,

    $IdAMUser,

    $IdAMPass,

    $APIKey,

    $ApiSecret

)
begin {
    if (-not ([System.Management.Automation.PSTypeName]'TrustAllCertsPolicy').Type) {
        Add-Type -TypeDefinition @"
            using System.Net;
            using System.Security.Cryptography.X509Certificates;
            public class TrustAllCertsPolicy : ICertificatePolicy {
                public bool CheckValidationResult(
                    ServicePoint srvPoint, X509Certificate certificate,
                    WebRequest request, int certificateProblem) {
                    return true;
                }
            }
"@ 
    }

}

process {
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy -ErrorAction SilentlyContinue
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    $Authorization = [Convert]::ToBase64String(
        [Text.Encoding]::ASCII.GetBytes(
            (
                "{0}:{1}" -f $snowUser , $snowPass
            )
        )
    )
    $ProxyAuthorization = [Convert]::ToBase64String(
        [Text.Encoding]::ASCII.GetBytes(
            (
                "{0}:{1}" -f $IdAMUser , $IdAMPass
            )
        )
    )
    $Headers = @{
        apikey                = $APIKey
        apikeySecret          = $ApiSecret
        "proxy-authorization" = "basic " + $ProxyAuthorization
        authorization         = "basic " + $Authorization
        "Content-Type"        = "application/json"
    }

    try {
        $TempDownloadLocation = $DownloadLocation# + "\" + $RITM
        $PathCheck = Test-Path -Path $TempDownloadLocation
        if ($PathCheck) { }
        else {
            $Tempresult1 = New-Item -ItemType Directory -Force -Path $TempDownloadLocation
        }
        $AttachmentResult = "NotFound"

        $RetrieveTableSysIdUri = $snowurl + "/api/now/table/sc_req_item?sysparm_query=number%3D$($RITM)&sysparm_limit=1"
        $RetrieveTableSysIdQuery = Invoke-RestMethod -Method Get -Uri $RetrieveTableSysIdUri -Headers $Headers
        $TableSysId = $RetrieveTableSysIdQuery.result.sys_id

        $RetrieveAttachmentLinkUri = $snowurl + "/api/now/attachment?sysparm_query=table_name%3Dsc_req_item%5Etable_sys_id%3D$($TableSysId)"
        $RetrieveAttachmentQuery = Invoke-RestMethod -Method Get -Uri $RetrieveAttachmentLinkUri -Headers $Headers
        $RetrieveAttachment = $RetrieveAttachmentQuery.result.download_link
$EachAttachment = $RetrieveAttachmentQuery.result[0]
            $RetrieveAttachment = $EachAttachment.download_link
            $EachAttachmentFileName = $EachAttachment.file_name
            $Split = ($EachAttachmentFileName -split '\.')
            if ($Split[1] -imatch $fileextenstion) {
                $FileName = $Split[0] + "_" + $RITM + "." + $Split[1];
                Invoke-RestMethod -Method Get -Uri $RetrieveAttachment -Headers $Headers -OutFile "$TempDownloadLocation\$($FileName)"
                $resultJson = [PSCustomObject]@{
                    FileName = $FileName
                    Result = "Found"
                } | ConvertTo-Json
                
            }
            if($resultJson.count -gt 0){
            
            $resultJson}else{
            "CSV not Found"
            }

    }
    catch {
        [PSCustomObject]@{
            FileName = $FileName
            Result = $_.Exception
        } | ConvertTo-Json
    }
}
end {
}