Smartsheet API Add attachment to Sheet using Powershell
I am building a Powershell module. Yes I know there is the C# SDK but I do not want that as a dependency for this Module.
I am struggling with this API Call:
Attach File or URL to Sheet
This is my code:
$BaseURI = "https://api.smartsheet.com/2.0"
$Id = {smartsheet id}
$filename = "MyDoc.docx"
$mimetype = "application/msword"
$Uri = "{0}/sheets/{1}/attachments" -f $baseUri, $id
$AuthCode = "{my auth code}"
$token = ConvertTo-SecureString -String $AuthCode -AsPlainText -Force
$response = Invoke-RestMethod - Method POST -Uri $Uri -Infile $filename -ContentType $mimetype -Authentication:Bearer -Token $Token
The response I get back from the API is:
{ "errorCode" : 1008, "message" : "Unable to parse request. The following error occurred: Request body must be either a JSON object or JSON array.", "refId" : "12y60zzovzndm" }
For sending a file this should work.
If I post to this API Call in Postman it works.
Answers
-
OK, got this to work.
Thanks to Postman's code example I did the following.
Created the headers as a hash table:
Name Value
---- -----
Content-Type application/vnd.openxmlformats-officedocument.wordprocessingml.document
Authorization Bearer VcjJj....
Content-Disposition attachment; filename="CWilliams.docx"
Notice I did not include Content-Length
read the input file into a byte array.
$body = [System.IO.File]::ReadAllBytes($path)
then issue the RestMethod call:
$response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $Headers -Body $body
This works. But according to the PowerShell docs we should not have to do it this way. The -InFile parameter should handle all the header setup and properly formulate the request.
Categories
- All Categories
- 14 Welcome to the Community
- Smartsheet Customer Resources
- 64.2K Get Help
- 419 Global Discussions
- 221 Industry Talk
- 461 Announcements
- 4.8K Ideas & Feature Requests
- 143 Brandfolder
- 142 Just for fun
- 58 Community Job Board
- 462 Show & Tell
- 32 Member Spotlight
- 1 SmartStories
- 299 Events
- 38 Webinars
- 7.3K Forum Archives