HTTP PUT request in Python using JSON data

amar19 picture amar19 · Sep 26, 2018 · Viewed 13.7k times · Source

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'>

Answer

blhsing picture blhsing · Sep 26, 2018

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}]