Powershell: Uploading file to Docparser API using Invoke-RestMethod - rest

$header = #{'Authorization'='Basic <auth code value>'}
$ping = Invoke-RestMethod -Uri "https://api.docparser.com/v1/ping" -Headers $header
ping works fine...returns "pong". I then make a request for the Parser ID which is needed for uploading documents. I am able to retrieve this value successfully.
$parser = Invoke-RestMethod -Uri "https://api.docparser.com/v1/parsers" -Headers $header
$parserID = $parser.id
Now here is where I try to upload a pdf, which fails.
$fileToParse = "C:\test.pdf"
$body = #{'file'=$fileToParse}
$uploadDoc = Invoke-RestMethod -Uri "https://api.docparser.com/v1/document/upload/$parserID" -Method Post -Headers $header -ContentType 'multipart/form-data' -Body $body
API response keeps saying "Error: input empty"
This is the documentation from Docparser on how to upload pdfs:
Any thoughts on what I'm doing wrong here? Thanks in advance,
Eric

The problem is that your body currently just contains the path to your local file. Docparser expects however the content of the file as multipart/form-data.
I never worked with PowerShell, but I think something like this should work for you:
$body = #{
"file" = Get-Content($fileToParse) -Raw
}
I got the code from this answer: How to send multipart/form-data with PowerShell Invoke-RestMethod

Related

How to POST Json file in the request body of Powershell Invoke-Webrequest

Can you please help me, How can I upload a Json file in the body of PUT request, is the following approach correct?
'''
$filename = "C:/Users/timtim/Downloads/default.json"
[hashtable]$headers=#{
'Authorization' = "Bearer $token"
}
$url= "url.com"
$statusCode = Invoke-WebRequest -Uri $url -Method PUT -InFile $filename -Headers $headers -ContentType "application/json"
Write-Host "$statusCode"
'''
Try this:
$filename = "C:/Users/timtim/Downloads/default.json"
$content = gc $filename
[hashtable]$headers=#{}
$headers.Add("Authorization", "Bearer $token")
$headers.Add('Content-Type', 'application/json')
$statusCode = Invoke-WebRequest -Uri $url -Method PUT -Body $content -Headers $headers
Write-Host $statusCode
Your syntax in the $headers was off. I replaced that part by initializing the hashtable, then we add our pieces to that one at a time. I was not sure why URL was in there so I removed it. You can add that back if needed. Send your JSON in a -body param. There is also $content = gc $filename where gc is an alias for "get-content". It's getting the content of the JSON from the file with that.

Using powershell Invoke-RestMethod to GET multipart content

I am trying to process a multipart GET call in powershell and then save the zipfile it contains to disk. I can execute this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers
and then echo out the filename and contents. In order to save the file, I tried this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "multipart/form-data" -Outfile result.zip
This raises an error (Invalid Operation). So I tried this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "application/zip" -Outfile result.zip
This creates a file called result.zip which isn't valid. I know that the response is multipart, so while this doesn't raise an error, I am not surprised that the file is invalid because it must contain all of the parts.
I have looked around, but all I find are ways of using Invoke-RestMethod to POST mulitpart content.
This is the error when I try to open the resulting zip file:
I have also tried to decode the result as below, but with the same results.
$B64String = $response.resultObject
Write-Host "resultObject size: $([Math]::Round($B64String.Length / 1Mb,2)) MiB"
$swDecode = [System.Diagnostics.Stopwatch]::StartNew()
$bytes = [System.Convert]::FromBase64String($B64String)
$swDecode.Stop()
Write-Host "Decoded size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"
Write-Output $bytes > $($response.fileName)
I found the answer
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers
$response | ConvertTo-Json
[IO.File]::WriteAllBytes($response.fileName, [System.Convert]::FromBase64String($response.resultObject))

Invoke-WebRequest -Method 'POST' with -ContentType 'application/json' Fails

When using:
$body = #{
Manager = "spmigrationuser#contoso.com" #$item.PMEmail
Name = "some name"
Number = "Some number"
Practice = "Some Practice"
}
$response = Invoke-RestMethod -Method Post -Uri $Url -Body $body -ContentType 'application/json' # -Headers $Headers
Or
$response = Invoke-WebRequest -Method 'POST' -Uri $Url -Body $body -ContentType 'application/json' # -Headers $Headers
Neither ContentType 'application/json'
Nor
$Headers = #{'Content-Type' = 'application/json' }
-Headers $Headers
Works
The error is always:
"Invoke-WebRequest : {"error":{"code":"InvalidRequestContent","message":"The request content is not valid and could not be deserialized: 'Error parsing NaN value. Path '', line 1, position 1.'."}}"
The same call works in Postman
I am using PS 5.1 and I must have -ContentType 'application/json' otherwise PS works but the service fails
What can be the issue?
I agree with NickSalacious. Your issue is that you are not sending JSON.
If you are using Postman and just starting to do API in PowerShell. Postman has a "Code" Link in the top right hand corner of the request. Just below and to the right of the Send button. In there you can select PowerShell. This will give you a good basis to see how the same request could be ran in PowerShell.
Postman would turn your body into this:
$body = "{`n `"Manager`": `"spmigrationuser#contoso.com`",`n `"Name`": `"some name`",`n `"Number`": `"Some number`",`n `"Practice`": `"Some Practice`"`n}"
This is not the easiest to work with and to read. Learning and using ConvertTo-Json is going to help a lot more in the long run.
*Edit: Also look at Invoke-RestMethod and Invoke-WebRequest. They behave differently and sometimes one will be better than the other.
*Edit2: Figured I would put an example of another way to do it.
$request = #{
Uri = 'http://YourURI.Here'
Headers = #{ 'Authorization' = $token
'AnotherHeader?' = 'Sure'}
Method = 'POST'
Body = '{
"Manager": $item.PMEmail,
"Name": "some name",
"Number": "Some number",
"Practice": "Some Practice"
}'
ContentType = 'application/json'
}
$response = Invoke-RestMethod #request
The API requires that the body be a JSON string. You can do a simple conversion (using ConvertTo-Json) in your Invoke-RestMethod command and set the content type accordingly.
Invoke-RestMethod -Method POST -Uri $uri -Header $header -Body ($body | ConvertTo-Json) -ContentType 'application/json'
Sorry I bothered all of you.
I tested on another computer and it works fine.

PowerShell - Slack API - Room History - Post method with x-www-form-urlencoded parameters

I want to pass a few body parameters using x-www-form-urlencoded format using powershell invoke-restmethod. Do not that this is working fine in PostMan. My code for this is below but is not working. How do I accomplish this in powershell?
$param = [System.Web.HttpUtility]::UrlEncode("channel:channelID
Content-Type:application/x-www-form-urlencoded
limit:50")
$uri="https://MySlackWebsite.com/api/channels.history"
$test2 = Invoke-RestMethod -Method POST -Uri $uri -Headers $headerJson -Body $param
I got this to work with the following using the guidance I got from #Erik Kalkoken.
$headerJson = #{Authorization="Bearer xoxp-xyz"}
$postParams = #{channel='roomID';limit=50}
$uri="https://slackserver.com/api/channels.history"
Invoke-RestMethod -Method POST -Uri $uri -Headers $headerJson -Body $postParams -ContentType "application/x-www-form-urlencoded"
Here is an example script on how to retrieve the list of messages from a channel with a POST request.
$postParams = #{token='xoxp-XXX';channel='C12345678'}
$test2 = Invoke-WebRequest -Uri https://slack.com/api/channels.history -Method POST -Body $postParams
Write-Host $test2
It tested and based on this answer about how to create a POST request with PowerShell.

Cant get a response from API Rest call with Powershell script

Im trying to send an API call to X and then the response will trigger some other things.
The issue i have is that im not getting any response in the ISE.
When im sending manually with fiddler/postman i get a response.
Im sending a simple post :
$Json = '{"Headers_In_Here"}}'
$Post = Invoke-WebRequest 'http://Server_URL' -Method Post -Body $Json -ContentType 'application/json'
Try adding ConvertTo-Json .
$Post = Invoke-WebRequest 'http://Server_URL' -Method Post -Body $Json -ContentType 'application/json' | ConvertTo-Json