Upload a file to an API using Powershell - powershell

I am trying to post a file to an API, which works perfectly under Linux using this curl command:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Token foo_bar' -F content=#'Filename.ending' 'http://test.test.com/api/upload'
I don't get how to work with the 'F' Parameter in curl on the Invoke-RestMethod/Invoke-WebRequest command. I tried:
Invoke-WebRequest -Uri $URL -Headers #{Authorization = 'Token '+foo_bar} -Method POST -ContentType 'multipart/form-data'
I tried adding -F 'C:\Users\Me\Filename.ending' to my command, I also tried using -InFile 'C:\Users\Me\Filename.ending', but I always get a response from the API telling me:
{"error":{"code":"GENERAL_ERROR","message":"missing uploaded file 'Filename.ending'"}}
Which probably suggests it wants the file in a different way. I also tried reading it in by Get-Content 'C:\Users\Me\Filename.ending' but had no success. What am I missing?

Related

Unable to use curl with double quote using powershell (Hubspot API)

I use Hubspot API.
I try to craete contact info.
Type this code using powershell (5.1version and 7.2)
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey"
--header 'content-type: application/json' -d "{\"properties\": {\"email\":\"$email\",\"firstname\":\"$firstname\"}}"
but error
return {"status":"error","message":"Invalid input JSON on line 1, column 3: Unexpected character ('\\' (code 92)): was expecting double-quote to start field name","correlationId":"2086b3bc-abe5-4f90-a79c-213d45bb2a97"}
I try this code using single quote after -d.
and then create contact info.
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey" --header 'content-type: application/json' -d '{\"properties\": {\"email\":\"xxx#yyy.co.jp\",\"firstname\":\"k\"}}'
but I want to substitute variables. So I want to use double quote.
I solved by myself.
put double-quotes and backslash between variable.
ConvertTo-Json
setting 2. to curl.exe
like this
$contactBody = #{
'"properties"' = #{
'"firstname"' = "`"$firstname`""
'"email"' = "`"$email`""
}
}
$contactBodyJson = ConvertTo-Json $contactBody
curl.exe --request POST --url "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$apiKey" --header 'content-type: application/json' -d $contactBodyJson

translate Postman post Request with Basic Auth to mingw64 curl and powershell On Windows 10

I would like to translate a POST Request test from Postman to curl on Windows!
note: ip, username, password are illustrative for this question!
Consuming from Postman, I get 200 OK Code fine!
But, Trying to use curl from cmd is not working!
Checking on Postman the curl code
I was trying on Powershell
curl --location --request POST 'http://10.31.7.52/BdN_SMS_CXP/api/SendSMS' --header 'Authorization: Basic bWFyaWVsYTpZMFMkaSRfViZTLjQwNio=' --header 'Content-Type: application/json' --data-raw '{"ANI" : 3007209820}'
curl --location --request POST 'http://10.31.7.52/BdN_SMS_CXP/api/SendSMS' --header 'Authorization: Basic bWFyaWVsYTpZMFMkaSRfViZTLjQwNio=' --header 'Content-Type: application/json' --data-raw '{\"ANI\" : 3007209820}'
checking codification/decodification is fine.
Now directly with user and password, according to https://stackoverflow.com/a/27442239/811293
curl --location --request POST 'http://10.31.7.52/BdN_SMS_CXP/api/SendSMS' --user 'mariela:Y0S$i$_V&S.406*' --header 'Content-Type: application/json' --data-raw '{"ANI" : 3007209820}'
Here my results.
When I use curl of mingw64 7.71.1 version, the command is misinterpreted, because I get a 407 error, Authentication required. It's not just a powershell problem solved with Remove-item alias:curl.
I suspect you should escape some characters, and use double commas " instead of single commas '.
What considerations should I have with $, _, &, . and * characters (if I should have it with any)?
How should I write the request in powershell (or mingw64 curl) for it to work?
The generated command is not powershell curl but cmd curl :
you can just use it in cmd as it is,
or if you want to use powershel use it as:
$command= "curl --location --request POST 'http://10.31.7.52/BdN_SMS_CXP/api/SendSMS' --header 'Authorization: Basic bWFyaWVsYTpZMFMkaSRfViZTLjQwNio=' --header 'Content-Type: application/json' --data-raw '{""ANI"" : 3007209820}'"
cmd /c $command

Azure DevOps problem to create project via REST call containing german umlauts

I have an admin script that creates Azure DevOps projects via calls to the REST API. This works fine as long as the name or description arguments contain no special characters. If for example german umlauts are in the description, the call fails.
This works:
curl -k -D- -X POST -d '{"name":"Phantom","capabilities":{"processTemplate":{"templateTypeId":"6b724908-ef14-45cf-84f8-768b5384da45"},"versioncontrol":{"sourceControlType":"Git"}},"visibility":"private","description":"Innocent description without umlauts"}' -H 'Accept: application/json' -H 'Content-Type: application/json' -H 'Authorization: Basic secretauthorizationtoken=' https://dev.azure.com/AdminPlayground/_apis/projects?api-version=6.0-preview.4
this one throws an exception:
curl -k -D- -X POST -d '{"name":"Phantom","capabilities":{"processTemplate":{"templateTypeId":"6b724908-ef14-45cf-84f8-768b5384da45"},"versioncontrol":{"sourceControlType":"Git"}},"visibility":"private","description":"Funny description with strange äöüß chars"}' -H 'Accept: application/json' -H 'Content-Type: application/json' -H 'Authorization: Basic secretauthorizationtoken=' https://dev.azure.com/AdminPlayground/_apis/projects?api-version=6.0-preview.4
The exception is:
{"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: projectToCreate","typeName":"System.ArgumentNullException, mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0}
Has anybody experienced similar behavior, and could perhaps suggest a solution?
Thanks!
This problem is due to the data format problem caused by the special characters in description.
Kindly check if it can be solved by adding the correct encoding format into the -ContentType,
For example -ContentType 'application/json;charset=utf -8'

Bad request when calling rest api using curl or Invoke-RestMethod

I want to convert speech to text using Microsoft speech-to-text service from within a bash script or PowerShell script. I tried using curl (Git bash) and Invoke-RestMethod (PowerShell) to send my 16 bit pcm mono wav audio file to the stt service.
The service is working, I used a c# example provided by Microsoft to test it. With the c# example I'm able to send the audio file and receive the text from the stt services.
Now I wanted to do this in a script.
Using curl in Git Bash:
curl -X POST "https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed" \
-H "Ocp-Apim-Subscription-Key: <my_subscription_key>" \
-H "Content-Type: audio/wav; codecs=audio/pcm; samplerate=16000" \
--data-binary audio.wav
Insufficient data to detect audio format: 7 bytes
Even using -d or --data or --data-raw instead of --data-binary doesn't change anything.
Using Invoke-RestMethod in PowerShell:
$audioBytes = [System.IO.File]::ReadAllBytes("c:\full\path\to\aduio\file.wav")
Invoke-RestMethod `
-Method Post `
-Uri "https://westeurope.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed" `
-Headers #{'Ocp-Apim-Subscription-Key' = '<my_subscription_key>'} `
-ContentType 'audio/wav; codecs=audio/pcm; samplerate=16000' `
-Body $audioBytes
Invoke-RestMethod: The remote server returned an error: (400) Bad Request.
Same error using -InFile audio.wav instead of -Body $audioBytes.
Am I missing something? Is there an error which I don't see?

Replicating curl POST with Invoke-RestMethod in PowerShell

I'm trying to replicate the following curl command in PowerShell:
linguist#qa:~ % curl -X POST -F text="Example lesson text" -F share_status=private \
-F title="Example Lesson Ttiel" -F collection=50510 \
-F image=#/home/lingq/Pictures/penguin.jpg \
-F tags=British -F tags=European
'https://www.lingq.com/api/languages/en/lessons/' -H 'Authorization: Token bd894eabcd4c0'
This is an API usage example from their page, I'm working with the assumption that it works. I don't know if it actually does, I don't have curl, and I don't want to have curl if possible.
I've been trying to recreate the command in PowerShell using the InvokeRestMethod function. So far what I got is this:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization","Token db3403c339fb4515c2940cccdcdcdbdcdbdcdbddc4cf453534453")
$response = Invoke-RestMethod -Method Post 'https://www.lingq.com/api/languages/ja/lessons/' -Headers $headers
I'm not even sure I'm adding the header with the token correctly, and I have no idea how to add the parameters that follow the -F in curl. I don't need image and tags, but the rest are crucial. Any ideas?
Edit: I have verified that the authentication token header works, by calling
Invoke-RestMethod -Method Get 'https://www.lingq.com/api/profile/' -Headers $headers
with my token and getting my profile.
I've also found out what the ominous -F means in curl, it's form data. So now I'm trying to figure out how to send 4 form data values in one Invoke-RestMethod call.
There is a similar question with this answer that should help you out. If you are having trouble with what the curl switches mean, you don't have to install it to look up its documentation.