25

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

1

3 Answers 3

24

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}]
Sign up to request clarification or add additional context in comments.

2 Comments

But this will not change the Content-Type in the request header to application/json
@dumbledad Why not? It's defined in the headers dict as posted in the OP's question.
13

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)

Comments

0
# Python examples

I used the following script to update mapped IP for a VIP object in FortiGate 
firewall. 

import requests
import urllib3

def update_vip(current_vip, new_vip, new_ip):
    urllib3.disable_warnings()        # disable HTTPS certificate verify warning
    json_body = {
        "name": new_vip,
        "id": 65535,
        "mappedip": [
            {
                "range": new_ip
            }
        ]
    }
    fgt_url = ("https://<FGT_IP>/api/v2/cmdb/firewall/vip/" + current_vip +
               ("?access_token=<accesstoken>"))
    res = requests.put(fgt_url, json=json_body, verify=False)

if __name__ == '__main__':
    current_vip = "VIP_Collector_SSH"
    new_vip = "VIP_Collector_SSH"
    new_ip = "172.16.31.32"
    update_vip(current_vip=current_vip, new_vip=new_vip, new_ip=new_ip)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.