I am currently having a problem with a script to send fuel transactions through an api. It works without variables:
$headers=@{}
$headers.Add("accept", "application/json")
$headers.Add("content-type", "application/json")
$headers.Add("authorization", "$APIToken")
$response = Invoke-WebRequest -Uri 'https://api.samsara.com/fuel-purchase' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"fuelQuantityLiters":"676.8","iftaFuelType":"Diesel","transactionLocation":"350 Rhode Island St, San Francisco, CA 94103","transactionPrice":{"amount":"640.2","currency":"usd"},"transactionReference":"5454534","transactionTime":"2024-02-22T10:20:50.52-06:00","vehicleId":"570"}'
But, with variables I get errors.
# A POSITIONAL PARAMETER CANNOT BE FOUND THAT ACCEPTS ARGUMENT ("" Around Body)
$response = Invoke-WebRequest -Uri 'https://api.samsara.com/fuel-purchase' -Method POST -Headers $headers -ContentType 'application/json' -Body "{"fuelQuantityLiters":$QuantityLiters,"iftaFuelType":$FuelType,"transactionLocation":$StationAddress,"transactionPrice":{"amount":$TransactionSale,"currency":$Currency},"transactionReference":$TransactionID,"transactionTime":$TransactionDateTime,"vehicleId":$Vehicle}"
# INVALID CHARACTER '$' LOOKING FOR BEGINNING OF VALUE ('' Around Body)
$response = Invoke-WebRequest -Uri 'https://api.samsara.com/fuel-purchase' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"fuelQuantityLiters":$QuantityLiters,"iftaFuelType":$FuelType,"transactionLocation":$StationAddress,"transactionPrice":{"amount":$TransactionSale,"currency":$Currency},"transactionReference":$TransactionID,"transactionTime":$TransactionDateTime,"vehicleId":$Vehicle}'
I figure it has to do with the quotations, but I’m not sure where I need to fix it. Here is the page with the api details about what I’m doing:
https://developers.samsara.com/reference/postfuelpurchase
2
Answers
You could try constructing the request-body JSON from a hastable like this –
That yields the JSON your after for the request body, then pass that to the API
In general, I find it is better to define everything ahead of time and just pass variables as parameters to Invoke-WebRequest.
I don’t have your situation to test this, but below is code similar to what I’ve been using for our own servers: