SPedraza
SPedraza

Reputation: 159

Invoke-RestMethod REST API PUT Method

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,

Upvotes: 8

Views: 41235

Answers (1)

rufer7
rufer7

Reputation: 4119

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;

Upvotes: 24

Related Questions