4
votes

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,

1
availability = @{ available = "Yes" }4c74356b41
That didn't do it, still having the same errorSPedraza
I never said it would do it I've just pointed out obvious error, also please fix your formatting4c74356b41
$data = $json | ConvertTo-Json => $json = $data | ConvertTo-Json. You have your variables backwards so you are sending $null effectively.Matt
Fixed that, still same errorSPedraza

1 Answers

17
votes

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;