I developed a bot to scrape some info via "API" in Python and now I want to change the stack to Powershell.
I'm having difficulties with one of the requests. In Python it works like a charm but on Powershell I'm unable to make it work in the same way.
In Python, I just create the payload
arrayWebCodes = ["PR1234", "PR3456"]
payloadStock={
"productsCN[]": arrayWebCodes ,
"productsCC[]": arrayWebCodes
}
response = s.post(urlStock, data=payloadStock)
This is because I want to obtain info for multiples products in a single call.
When I try to implement same on Powershell, response is empty.
$arrayProducts = @("PR1234", "PR73456")
$payloadStock = [ordered]@{
"productsCN[]" = $arrayProducts
"productsCC[]" = $arrayProducts
}
$response = Invoke-WebRequest -Uri $urlStock -body $payloadStock -Method "POST" -WebSession $webSession
Somehow, Powershell Hashtables of Arrays have some differences with Python dictionary of arrays I'm trying to implement here.
If I implement the request with only one code in Powershell, it works. So if I go from:
$codProduct1 = "PR1234"
$codProduct2 = "PR3456"
$payloadStock = [ordered]@{
"productsCN[]" = $codProduct1, $codProduct2
"productsCC[]" = $codProduct1, $codProduct2
}
$response = Invoke-WebRequest -Uri $urlStock -body $payloadStock -Method "POST" -WebSession $webSession
to:
$codProduct1 = "PR1234"
$codProduct2 = "PR3456"
$payloadStock = [ordered]@{
"productsCN[]" = $codProduct1
"productsCC[]" = $codProduct1
}
$response = Invoke-WebRequest -Uri $urlStock -body $payloadStock -Method "POST" -WebSession $webSession
It Works...
I'm about to quit, any help is really appreciated.
Not really the answer to your issue, but just to be sure.
This should be the same:
import json
arrayWebCodes = ["PR1234", "PR3456"]
payloadStock={
"productsCN[]": arrayWebCodes ,
"productsCC[]": arrayWebCodes
}
print(json.dumps(payloadStock))
{"productsCN[]": ["PR1234", "PR3456"], "productsCC[]": ["PR1234", "PR3456"]}
$arrayProducts = @("PR1234", "PR73456")
$payloadStock = [ordered]@{
"productsCN[]" = $arrayProducts
"productsCC[]" = $arrayProducts
}
$payloadStock | ConvertTo-Json -Compress
{"productsCN[]":["PR1234","PR73456"],"productsCC[]":["PR1234","PR73456"]}
I suspect that the Invoke-WebRequest -body
might have the same -Depth
default issue as for unexpected ConvertTo-Json
results? Answer: it has a default -Depth
of 2
.
What happens if you provide the -body
as a (json) string:
$jsonPayload = $payloadStock | ConvertTo-Json -Compress -Depth 9
$response = Invoke-WebRequest -Uri $urlStock -body $jsonPayload -Method GET -WebSession $webSession