I've been successfully using Invoke-WebRequest to post requests to a REST-based API from PowerShell.
Invoke-WebRequest -UseBasicParsing -ContentType "application/json" -Method POST -Body $jsonToday I came across Invoke-RestMethod which sounds more aptly-named for what I'm doing. What is the difference, and is there a reason to use one over the other?
2 Answers
You can find out by decompiling the Microsoft.PowerShell.Commands.Utility assembly.
Basically, Invoke-WebRequest does not deal with parsing the data all that much. With -UseBasicParsing, it does some Regex-based HTML parsing. Without this switch, it’ll use the Internet Explorer COM API to parse the document.
That’s it. It’ll always attempt to parse HTML.
Invoke-RestMethod on the other hand has code to support JSON and XML content. It’ll attempt to detect an appropriate decoder. It does not support HTML (except for XML-compliant HTML, of course).
Both share the same core logic to make the actual HTTP request. It’s only in result processing that they differ.
Seeing is believing!
PS C:\Users\fuzzy> (Invoke-RestMethod ).headers
Connection Host User-Agent
---------- ---- ----------
close httpbin.org Mozilla/5.0 (Windows NT; Windows NT 10.0; de-DE) WindowsPowerShell/5.1.15063.483
PS C:\Users\fuzzy> Invoke-WebRequest -UseBasicParsing
StatusCode : 200
StatusDescription : OK
Content : { "headers": { "Connection": "close", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (Windows NT; Windows NT 10.0; de-DE) WindowsPowerShell/5.1.15063.483" } }
RawContent : HTTP/1.1 200 OK Connection: keep-alive Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true X-Processed-Time: 0.00075101852417 Content-Length: 180 Content-Type: application/json...
Forms :
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials, true], [X-Processed-Time, 0.00075101852417]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml :
RawContentLength : 180 systemcenterautomation.com did a blog post about this. The conclusion:
Invoke-RestMethodis much better at dealing with XML and JSON results, whileInvoke-WebRequestis better at dealing with straight HTML results