2

I am trying to use the REST API with Octoprint

My code is as follows:

import requests
import json


api_token = '7598509FC2184985B2B230AEE22B388F'
api_url_base = 'http://10.20.10.189/'

api_url = '{}{}'.format(api_url_base, 'api/job')

headers = {
         'Content-Type': 'application/json',
         'apikey': api_token,
         '"command"': '"pause"',
         '"action"': '"pause"'
          }

response = requests.post(api_url, headers=headers)

print(response)

my result is

<Response [400]>

I am kind of at a loss at the moment

Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
  • an HTTP 400 "Bad Request" response is telling you that the server could not understand the request due to invalid syntax. Something in your request is malformed. – pbarney Sep 06 '17 at 22:00

3 Answers3

0

Im working on something similar.

This code is function:

import json
import urllib3

ip_address = '192.168.1.55'
apikey = 'CA54B5013E8C4C4B8BE6031F436133F5'
url = "http://" + ip_address + '/api/job'
http = urllib3.PoolManager()

r = http.request('POST', 
                 url,
                 headers={'Content-Type': 'application/json', 
                          'X-Api-Key': apikey},
                 body=json.dumps({'command': 'pause',
                                  'action': 'pause'}))
Tibor
  • 81
  • 1
  • 7
0

I have never used octoprint and requests. This is a best effort answer from the documentation and the knowledge that normally you must separate the headers and the POST data.

import requests
import json


api_token = '7598509FC2184985B2B230AEE22B388F'
api_url_base = 'http://10.20.10.189/'

api_url = '{}{}'.format(api_url_base, 'api/job')

headers = {
         'Content-Type': 'application/json',
         'X-Api-Key': api_token # the name may vary.  I got it from this doc: http://docs.octoprint.org/en/master/api/job.html
          }
data = {
         'command': 'pause', # notice i also removed the " inside the strings
         'action': 'pause'
          }

response = requests.post(api_url, headers=headers, data=data)

print(response)
RedX
  • 14,749
  • 1
  • 53
  • 76
0

I have also been dealing with this problem (Octoprint API) for a long time. Urllib3 example here is functional, but when I ported it to python3 requests, I got <Response [400]>.

response = requests.post(api_url, headers=headers, data=data)

The magic is in this (json=data) <Response [204]>

response = requests.post(api_url, headers=headers, json=data)