简体   繁体   中英

Convert Curl to Invoke-RestMethod

Problem

I am having a hard time converting a curl call into a Powershell Invoke-RestMethod call as Powershell doesn't really thow the most informative error messages (if any).

Curl call (Ubuntu)

token = "djsakldsakldjaslda"
host = "https://lalala.azuredatabricks.net/"
curl -X POST -H "Authorization: Bearer $(token)" $(host)/api/2.0/clusters/create -d $(cat my_file.json)

Invoke-RestMethod call (Powershell)

$token= "djsakldsakldjaslda"
$host = "https://lalala.azuredatabricks.net/"
Invoke-RestMethod -Method Post -Uri $host/api/2.0/clusters/create -Headers @{"Authorization" = "Bearer " + $token} -Body $(get-content my_file.json -raw | ConvertFrom-Json)

I have various formats for the body, but no matter what I send, I just get some HTML back for a login page. On Ubuntu with Curl everything works perfectly.

NOTE:
The problem seemed to be that PowerShell cannot handle double-"/" as in "https://lalala.azuredatabricks.net//api/2.0/clusters/create".

The strange part is that Invoke-RestMethod gets to the login page, but fails from there.

Use -InFile to upload a file. Don't forget to set the content type.

Wrapped for legibility (escaping the EOL works as line continuation in PowerShell, it looks funny because StackOverflow syntax highlighting cannot handle it):

Invoke-RestMethod `
    -Method Post `
    -Uri "$host/api/2.0/clusters/create"
    -Headers @{
        Authorization = "Bearer $token"
    } `
    -Infile my_file.json
    -ContentType "application/json"

The body is expected to be JSON format, when you take the file and add the | ConvertFrom-Json | ConvertFrom-Json the content becomes a PowerShell object.

So, you can remove the | ConvertFrom-Json | ConvertFrom-Json and it should work:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM