Python Post Command to Samsung TV API

Hello, I want to make a Python Script which send the Key Command to the API. In the docs it says:

The integration supports the remote platform. The remote allows you to send key commands to your TV with the remote.send_command service. The supported keys vary between TV models.

Full keycodes list

Example to send sequence of commands:

service: remote.send_command
target:
  device_id: 72953f9b4c9863e28ddd52c87dcebe05
data:
  command:
    - KEY_MENU
    - KEY_RIGHT
    - KEY_UP
    - KEY_UP
    - KEY_ENTER

I wrote a small Python Script. which is this:

import requests

url = "http://192.168.10.26:8123/api/services/remote/send_command"
headers = {
    "Authorization": "Bearer <TOKEN>",
    "Content-Type": "application/json"
}
data = {
    "target": {
        "device_id": "01HP1GET9FCKVQTFZAFGDA2QYR"
    },
    "data": {
        "command": "KEY_HOME"
    }
}

response = requests.post(url, headers=headers, json=data)
print(response.text

But I got 400 Bad Request. What did I wrong?

I have one more item in my header. I can’t remember where I found that info or if it’s necessary, but it’s worth a try. Specifically:

"Accept": "application/json"

Also, I think you have to convert the JSON dict to an actual string to send it using requests. At least that’s what I do when I’m sending JSON via the requests module. So instead of json=data in your call, try json=json.dumps(data). You need to add import json to use that.

1 Like

The right code for this is:

import requests
import json

import requests
import json

url = "http://192.168.10.26:8123/api/services/remote/send_command"
headers = {
    "Authorization": "Bearer <TOKEN>",
    "Content-Type": "application/json",
    "Accept": "application/json"
}
data = {
    "entity_id": "remote.fernseher",
    "command": "KEY_HOME"
}

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()  # Überprüfen Sie auf Fehlerstatuscodes
    print("Anfrage erfolgreich gesendet.")
except requests.exceptions.RequestException as e:
    print("Fehler bei der Anfrage:", e)