Format python PATCH request from curl command

Viewed 921

I have a curl command I can run from my local machine that works, but transferring it to a python script is giving me difficulties. Here's the curl command that works:

curl -X PATCH "http://localhost:9999/pins/1" -H "Content-Type: application/json" -d "{"state": "on"}"

And here is what I have so far as a python request:

import requests

url = 'http://localhost:9999/pins/1'
payload = {'state':'on'}
head = {'Content-Type':'application/json'}

r = requests.patch(url, payload, headers=head)

But I am receiving a 400 response. Any direction?

Also, if I format it as

r = requests.patch(url, data=payload)

I get a 500 response code. Also should be noted: I can run a simple get request easily by running something like

r = requests.get(url)
2 Answers
import requests

url = 'http://localhost:9999/pins/1'
payload = {'state':'on'}
head = {'Content-Type':'application/json'}

r = requests.patch(url, json=payload)

change this r = requests.patch(url, data=payload) to r = requests.patch(url, json=payload)

Try the following to make sure that your payload is valid json.

import requests
import json

url = 'http://localhost:9999/pins/1'
payload = {'state':'on'}
head = {'Content-Type':'application/json'}

r = requests.patch(url, data=json.dumps(payload), headers=head)
Related