Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP PUT request in Python using JSON data

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

like image 590
amar19 Avatar asked Sep 26 '18 05:09

amar19


People also ask

How do you pass JSON data in a POST request in Python?

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.

How do I send a POST request with JSON payload?

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.

How does put work in Python?

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.


1 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}]
like image 51
blhsing Avatar answered Sep 17 '22 11:09

blhsing