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'>
To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.
To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.
The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With