Calling HASS API from Various Shells

While working on making my macro pad trigger Home Assistant automations, I found the API would be the easiest way to integrate the systems. Here’s some of my experimenting with the API and how to call it from Linux curl and PowerShell Invoke-WebRequest

Linux Curl

Using the Linux curl command is pretty straight forward.

curl -X POST http://hass.local:8123/api/services/switch/toggle -H 'Authorization: Bearer ABCDEF' -d '{"entity_id": "switch.testsubject_test_subject"}'

PowerShell Invoke-WebRequest

PowerShell is a bit more annoying to get everything right, as Invoke-WebRequest is a bit pickier on its input arguments.

Invoke-WebRequest -Method POST -Uri "http://hass.local:8123/api/services/switch/toggle" -H @{"Authorization"="Bearer ABCDEF"} -Body '{"entity_id": "switch.testsubject_test_subject"}'

Apparently windows has a build of the official Unix curl and tar commands, but my PowerShell prompts all had curl as an alias to Invoke-WebRequest. I did find that if i call curl.exe, it would run the official curl command.

Conclusion

Do be careful when copying and pasting between shells, I found that copying out of the PowerShell prompt and back in would yield an invalid token. This was also encountered in the WSL terminal as well.

The API is pretty straight forward after a little bit of trying things out. The documentation covers the capability but doesn’t have as many examples as I would have liked otherwise.

Resources