Search code examples
node.jsresthttprequestoctoprint

How do a pass commands through the OctoPrint Rest API?


What I'm trying to do is use the OctoPrint Rest API. I keep running into an error though when I'm trying to do POST requests that require a command. Here's an example of that in the docs.

POST /api/connection HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...

{
  "command": "connect",
  "port": "/dev/ttyACM0",
  "baudrate": 115200,
  "printerProfile": "my_printer_profile",
  "save": true,
  "autoconnect": true
}

What I'm most confused about is where I include the command or the port values. Here's what I'm currently doing.

var self = this;

    request({
        url: OCTOIP + "/api/connection",
        method: "POST",
        "content-type": "application/json",
        headers: {
            "X-Api-Key": KEY
        },
        body: JSON.stringify({"command": "connect"})

    }, function(error, response, body) {
        //var info = JSON.parse(body);
        if (error) {
            console.log(error);
            self.tell("Could Not Connect");
        }
        else {
            console.log(body);
            self.tell("Connected to printer.");
        }
    });

What happens is I keep getting this error message.

Expected content-type JSON

I've tried changing content-type to just json, I've tried getting rid of the JSON.stringify and just putting it as {"command": "connect"}. Or even dropping the curly brackets altogether. Another thing I tried was using form and instead of the body. None of those have worked. What am I doing wrong here?


Solution

  • Fixed the issue. It turns out it wasn't working because I didn't put the content-type in the header.