Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke-RestMethod REST API PUT Method

Tags:

powershell

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,

like image 697
SPedraza Avatar asked Mar 27 '17 16:03

SPedraza


People also ask

What does Invoke-RestMethod return?

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.

What is the difference between invoke-RestMethod and invoke-WebRequest?

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.

How do I use REST API in PowerShell?

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.


1 Answers

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;
like image 91
rufer7 Avatar answered Oct 25 '22 13:10

rufer7