HTTP PUT request in Python using JSON data

26,410

Solution 1

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

Solution 2

HTTP methods in the requests library have a json parameter that 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)
Share:
26,410
amar19
Author by

amar19

Updated on July 09, 2022

Comments

  • amar19
    amar19 almost 2 years

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