I have a web server that responds to a request https://localhost/GetUpdateInfo with a body [{"ipAddress": "10.200.2.55"}]
In postman its Work but in powershell i can`t do this because body begins from array.
When i do exmple code:
$Url = "https://localhost/GetUpdateInfo"
$Body = #(#{
ipAddress = "10.200.2.55"
})
$jsonBody = ConvertTo-Json -InputObject $Body
Invoke-RestMethod -Method 'Post' -Uri $url -Body $jsonBody
i hve error: Invoke-RestMethod : Block length does not match with its complement.
The content type of all POST requests is application/x-www-form-urlencoded unless specified.
Add -ContentType application/json to your last line call so your json is sent correctly.
Invoke-RestMethod -Method 'Post' -Uri $url -Body $jsonBody -ContentType 'application/json'
Related
I'm trying to create a powershell script to access JoeSandBox API to download reports.
I'm following their API details there https://www.joesandbox.com/userguide?sphinxurl=usage/webapi.html
Here's the beginning of the REST script I've put together:
$json = #{
apikey="XXXX";
webid= "YYYY"
} | ConvertTo-Json
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -Body $json -ContentType 'multipart/form-data'
Basically, I don't get the access...
Invoke-RestMethod : {"errors":[{"code":2,"message":"apikey is required."}]}
Thanks
$body = #{'apikey'='XXX'; 'webid'='YYY'}
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -body $body
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.
I'm sending a POST request with ID/password and I need to get back a respond token, how can I get it and save it for later use in the script?
$loginUrl = "https://some-ip"
$params = #{
"username"="$username"
"password"="$password"
}
Invoke-WebRequest -Uri $loginUrl -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"
Following your input:
$url = "https://some-ip"
$params = #{
"username" = $username
"password" = $password
} | ConvertTo-Json
$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json"
$apiReturn can then be used as response.
Furthermore, you can use the SessionVariable parameter of Invoke-RestMethod.
$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json" -SessionVariable sessionToken
$sessionToken.Headers.Add('Authorization', $apiReturn)
$sessionToken.Headers.Add('Content-Type', 'application/json')
In this scenario, you add the response token to 'Authorization' and forward the whole token to your subsequent API calls. Like this you only need to add $sessionToken and Content-Type for example is already provided.
Invoke-RestMethod -Method Post -Uri $url -WebSession $sessionToken
You can add more parameters to your Header in case it is required.
I added powershell script in azure devops release and try to send POST request using Invoke-WebRequest with Authorization token and xml file.
What am I doing wrong?
I get Authorization token from another POST request and tried to create headers with this token and trying send xml file using x-ray endpoint (NUnit XML results - POST /api/v1/import/execution/nunit)
https://confluence.xpand-it.com/display/XRAYCLOUD/Import+Execution+Results+-+REST#ImportExecutionResults-REST-NUnitXMLresults
Authorization token like headers parameters
Content-type like powershell parameters
$bodyForAuth=#{"client_id"="...";
"client_secret"="...";
}
$jsonAuth=Invoke-WebRequest -Uri $urlForAuth -Method POST -Body ($bodyForAuth|ConvertTo-Json) -ContentType "application/json"
$authToken=ConvertFrom-Json -InputObject $jsonAuth
$headers=#{ Authorization = "Bearer $authToken" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -ContentType "text/xml" -InFile $TestResultsXmlPath
And I have error: "Invoke-RestMethod : Could not find authentication data on request"
Also I try to send like this:
$headers=#{ Authorization = "Bearer $authToken";"Content-Type"="text/xml" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -InFile $TestResultsXmlPath
And also have the same error : "Invoke-RestMethod : Could not find authentication data on request"
But if I send POST request like this (without Content-Type):
$bodyForAuth=#{"client_id"="...";
"client_secret"="...";
}
$jsonAuth=Invoke-WebRequest -Uri $urlForAuth -Method POST -Body ($bodyForAuth|ConvertTo-Json) -ContentType "application/json"
$authToken=ConvertFrom-Json -InputObject $jsonAuth
$headers=#{ Authorization = "Bearer $authToken" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -InFile $TestResultsXmlPath
I have SERVER ERROR: "Invoke-RestMethod : {"error":"Missing data in the nunit results import request"}"
Power Shell v. 5.1
Why when I send to headers server can not fine authorization data?
I needed parenthesis, so I changed $TestResultsXmlPath to $(TestResultsXmlPath)
Invoke-WebRequest `
-Headers $headers `
-Uri $urlForXrayApi `
-Method POST `
-InFile $(TestResultsXmlPath)
I have a very basic requirement to call a RESTful API. I am currently on a Windows 2012 R2 server using version 4 of PowerShell.
Here is my code:
$logon = #{
username = 'blah'
password='blah'
}
$body = $logon | ConvertTo-Json
$URI = 'https://URL/Logon'
Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose
I get the following result:
{"LogonResult":"blahblahblah"}
How do I extract just the logon token to reuse as a variable? I've already put a variable at the beginning of the command:
$token = (Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content
This returns the entire result, not just the token. How do I get just the token as a result?
You can get the value of the returned LogonResult property as follows:
$token = ((Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content | ConvertFrom-JSON).LogonResult
Or you simplify this by using Invoke-RestMethod as this returns just the content and converts it to a PSObject automatically:
$token = (Invoke-RestMethod -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).LogonResult