Converting CURL to POST in Python

So basically I’m trying to convert this curl call to a Python Post message using requests.
The program I’m using is controlled by the args at the end.

curl https://api.spark.io/v1/devices/<ID>/params \-d access_token=<token> \-d “args=mode=3,brightness=140”

My python code looks like this:

import requests
   
headers = {'content-type': 'application/json'}

function = 'params'
access_id = 'XXX'
access_token = 'XXX'
payload = {'access_token': access_token}
url = 'https://api.spark.io//v1/devices/' + access_id + '/' + function

data = {'access_token': access_token, 'args': 'red_energy=0'}

r = requests.post(url, data=json.dumps(data))

However, I continuously get a 400 error stating that “The access token was not found”. I’ve checked the access token and ID and they are both correct.

(params is the function call btw)

Any suggestions?

This seems to work for me:

3 Likes

It worked. The error was extremely simple…the url was misspelled and the JSON.dumps was mutating the data in the wrong format.

Thanks!

1 Like

I know this isn’t a POST, but this thread could use a bump as things have changed a bit. You’ll notice in the example spark.io is still being called. This should now be particle.io. I have included a sample get request that will help “get” folks started.

I am using the dotenv python package to manage my sensitive data in a .env file located at the same level as the script in the file system. I’d highly recommend this practice so that you can commit your code without worrying about accidentally committing sensitive data.

import os
from dotenv import load_dotenv
import requests

load_dotenv()

access_token = os.getenv("ACCESS_TOKEN")
device_id = os.getenv("DEVICE_ID")

#Sample GET request
address = 'https://api.particle.io/v1/devices/{0}'.format(device_id)
headers = {'Authorization':'Bearer {0}'.format(access_token)}
get = requests.get(address, headers=headers)


print(get.text)