Your data is already a JSON-formatted string. You can pass it directly to requests.put instead of converting it with json.dumps again.
Change:
response = requests.put(url, data=json.dumps(data), headers=headers)
to:
response = requests.put(url, data=data, headers=headers)
Alternatively, your data can store a data structure instead, so that json.dumps can convert it to JSON.
Change:
data = '[{"$key": 8},{"$key": 7}]'
to:
data = [{"$key": 8},{"$key": 7}]
Answer from blhsing on Stack OverflowYour data is already a JSON-formatted string. You can pass it directly to requests.put instead of converting it with json.dumps again.
Change:
response = requests.put(url, data=json.dumps(data), headers=headers)
to:
response = requests.put(url, data=data, headers=headers)
Alternatively, your data can store a data structure instead, so that json.dumps can convert it to JSON.
Change:
data = '[{"$key": 8},{"$key": 7}]'
to:
data = [{"$key": 8},{"$key": 7}]
HTTP methods in the requests library have a json argument that, when given, will perform json.dumps() for you and set the Content-Type header to application/json:
data = [{"$key": 8},{"$key": 7}]
response = requests.put(url, json=data)
How can I POST JSON data with Python's Requests library? - Stack Overflow
APIs: Params= vs json= whats the difference?
Put request using python
Working with API, JSON in Python
Videos
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:
>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
'data': '{"key": "value"}',
'files': {},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '16',
'Content-Type': 'application/json',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
'X-Request-Id': 'xx-xx-xx'},
'json': {'key': 'value'},
'origin': 'x.x.x.x',
'url': 'http://httpbin.org/post'}
It turns out I was missing the header information. The following works:
import requests
url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
Been learning more about accessing APIs and stuff. I keep running into things about params and json to do requests. I don't exactly understand what the difference between these two is. I use the same dictionaries but the keyword differs.
I tried to read the documentation but its a bit more technical than my ability.