Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Trouble uploading attachment to ServiceNow (attachments API)

Mike Hashemi
Kilo Sage

I am trying to upload a text file, to attach to an unpublished Knowledge article in the Utah release of ServiceNow.

My code is:

 

$uri = "https://instanceName.service-now.com/api/now/attachment/upload"
$method = "POST"
$filePath = "C:\it\test.txt"
$headers = @{
"Accept" = "application/json"
}
$uploadResult = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Credential $credential -ContentType "multipart/form-data" -Form @{
"table_name" = "kb_knowledge"
"table_sys_id" = "fcd86f8fc314b5500240d1ec7a01319f" # Sys_id of the article, to which the file should be attached.
"uploadFile" = Get-Item -Path $filePath
}

 

It looks to me, like the account represented in $credential can add attachments (it can definitely create KM articles).

The error:

  • Invoke-RestMethod: {"error":{"message":"Missing parameter: table_name","detail":null},"status":"failure"}

I tried wrapping the form value fields in double quotes (and single quotes, same behavior):

$uploadResult = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Credential $credential -ContentType "multipart/form-data" -Form @{
table_name = "`"kb_knowledge`""
table_sys_id = "`"fcd86f8fc314b5500240d1ec7a01319f`"" # Sys_id of the article, to which the file should be attached.
uploadFile = "`"$(Get-Item -Path $filePath)`""
}

But that only resulted in a different error:

  • Invoke-RestMethod: {"error":{"message":"Failed to create the attachment. File part might be missing in the request.","detail":null},"status":"failure"}

I am certain that a file exists at C:\it\test.txt. Also, I am using /upload instead of /file (https://developer.servicenow.com/dev.do#!/reference/api/utah/rest/c_AttachmentAPI#attachment-POST-up...) because I want to avoid having to figure out the mime type of the file.

 

What gives?

1 ACCEPTED SOLUTION
2 REPLIES 2

But that example users /file, not /upload.

 

I'll give it a try, but I'm pretty sure I want the form upload.