Search code examples
pythonpython-requestsoctoprint

OctoPrint API, error 400 when making a POST request


I'm working with Octoprint's API. I'm struggling trying to issue commands to the 3d printer.

For example, I want to issue a command that makes the 3d printer jog the X-axis.

import requests
headers = {"Authorization": "Bearer <token>"}

def Beep():
  api_link = "http://octopi.local/api/printer/command"
  params = {"command":"jog","x":10}
  return requests.post(api_link, headers=headers, params=params)

The output of this code is <Response 400> (bad request). What I am missing?


Solution

  • From the API documentation:

    If not otherwise stated, OctoPrint’s API expects request bodies and issues response bodies as Content-Type: application/json.

    Your request is not sending JSON. Use this instead:

    requests.post(api_link, headers=headers, json=params)
    

    Also, it looks like the jog command is supposed to use the url path /api/printer/printhead.