Smartsheet API Add attachment to Sheet using Powershell

Options

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

  • Cliff Williams
    Options

    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.