HTTP PUT request in Python using JSON data

Question:

I want to make PUT request in Python using JSON data as

data = [{"$TestKey": 4},{"$TestKey": 5}]

Is there any way to do this?

import requests
import json

url = 'http://localhost:6061/data/'

data = '[{"$key": 8},{"$key": 7}]'

headers = {"Content-Type": "application/json"}

response = requests.put(url, data=json.dumps(data), headers=headers)

res = response.json()

print(res)

Getting this error

requests.exceptions.InvalidHeader: Value for header {data: [{'$key': 4}, {'$key': 5}]} must be of type str or bytes, not <class 'list'>

Asked By: amar19

||

Answers:

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}]
Answered By: blhsing

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)
Answered By: monkut
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.