How should I POST binary data (e.g. an image) the proper way?

How do you POST binary data? In my specific case, I want to send an image to Matrix/Synapse messenger.

I’m migrating from OpenHAB where used a workaround like this:

// OpenHAB natively can't send binary data but you can Base64 encode binary data
var Base64 = Java.type("java.util.Base64")
var result = actions.HTTP.sendHttpPostRequest(
    "https://example.com/upload", "application/json",
    JSON.stringify({
        filename: "snapshot.jpg",
        data: Base64.getEncoder().encodeToString(Java.to(imageData, "byte[]"))
    }), 3000
);

First I tried rest_scripts, but it cannot figure out how to send binary data either.

Second I tried python_scripts. Either to send binary data directly, or to base64 encode the data. But I couldn’t figure this out as the python_scripts don’t allow import statements :slight_smile:

# Doesn't work
import requests

with open(image_path, "rb") as f:
    data = f.read()

request('POST', 
    f'https://example.com/upload?filename={filename}', 
    body=data, 
    headers=headers)
# Doesn't work
import base64

with open(image_path, "rb") as f:
    data = f.read()

print(base64.b64encode(binary).decode())
exit(0)

Finally I tried shell_scripts to run curl:

shell_command:
  matrix_snapshot: >
    curl -X POST 
    -H "Content-Type: image/jpeg" 
    -H "Authorization: {{ bearer }}"
    --data-binary "@{{ filename }}"
    https://example.com/upload?filename=snapshot.jpg

This works, but it doesn’t feel right. It’s a hack using a long string escape disaster waiting to happen if I start expanding on this. Hoping curl will remain available in the shell.

Are there prettier solutions available that I’m just missing? I still consider myself a novice in Home Assistant.

pyscript:
  allow_all_imports: true
  hass_is_global: true

I have this in my configuration.yaml, but not sure if it helps.

Thank you for thinking with me. I will consider a third party integration plan C, being that my current native approach is plan B.

pyscript is a third party integration. I read that it is considered complex and a security risk. I’m specifically trying to do this in a Home Assistant native way. My current (ugly) solution is done using native integrations only. I’m looking to learn of a better native method I can call plan A. I’m not sure why @Sir_Goodenough moved this to Third Party Integrations.