I am trying to use the PUT
method in my REST API
and I think I have syntax issues. So far this is what I have:
$url3 = "example.com"
$contentType3 = "application/json"
$basicAuth3 = get_token
$headers3 = @{
Authorization = $basicAuth3
};
$data = @{
userId = "_39_1";
courseId = "_3_1";
availability = {
available = "Yes"
};
courseRoleId = "Student"
};
$json = $data | ConvertTo-Json;
Invoke-RestMethod -Method PUT -Uri $url3 -ContentType $contentType3 -Headers $headers3 -Body $json;
I don't think the Invoke-RestMethod
is able to read the $json
variable and that is why it is giving me an error. Any suggestions?
The error I am getting is the following:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request. At E:\PowerShell\Get_User_Enroll.ps1:62 char:1 + Invoke-RestMethod -Method PUT -Uri $url3 -ContentType $contentType3 -Headers $he ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Best,
The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.
Invoke-RestMethod - unlike Invoke-WebRequest - has deserialization built in: with a JSON response, it automatically parses the JSON text returned into a [pscustomobject] graph as if ConvertFrom-Json had been applied to it.
To call a REST API from the Windows PowerShell, you should use the Invoke-RestMethod cmdlet. A call to an API is simply a request through HTTP or HTTPS. So, you will need a URL to which the API will be sent. You can find detailed information about the URL to call to get data from API documentation.
You have to create another hashtable for availability. You missed the @
before the {
of the availability object.
$url3 = "myurl";
$contentType3 = "application/json"
$basicAuth3 = get_token
$headers3 = @{
Authorization = $basicAuth3
};
$data = @{
userId = "_39_1";
courseId = "_3_1";
availability = @{
available = "Yes"
};
courseRoleId = "Student"
};
$json = $data | ConvertTo-Json;
Invoke-RestMethod -Method PUT -Uri $url3 -ContentType $contentType3 -Headers $headers3 -Body $json;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With