I am trying to write a python script to GET and POST to octoprint

1.4k Views Asked by At

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

3

There are 3 best solutions below

0
On

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)
0
On

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'}))
0
On

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)