Reputation: 1782
I'm quite new to using api's.
I'm using requests.patch()
to access an api to switch a remote device by sending a list of switches with their required status. I have the headers set up as a dict, with one of the values being the list of switches; this corresponds with the api documentation.
data = {"Authorization" : "Bearer key_xxxxxxx",
"id": "d1234",
"switches": [{"id": "s1",
"state": "open"},
{"id": "s2",
"state": "closed"}
]}
r= requests.patch(url, headers=data)
I get the following exception:
requests.exceptions.InvalidHeader: Value for header {switches: [{'id': 's1', 'state': 'open'}, {'id': 's2', 'state': 'closed'}]} must be of type str or bytes, not <class 'list'>
The api manual is clear that the switches are sent as a list, and this is how they are returned from requests.get()
, so the exception seems to be related to requests
syntax rather than being specific to the api.
I obviously can't post the actual script with api key etc, so am hoping someone can spot an error in the code above.
Upvotes: 0
Views: 5217
Reputation: 820
Pass payload and headers as a separate entity from the patch function as:
header = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxxxx"}
data = [{"id": "d1234",
"switches": [{"id": "s1",
"state": "open"},
{"id": "s2",
"state": "closed"}
]}]
r= requests.patch(url, data=json.dumps(data), headers=header)
Please read the docs
Upvotes: 0
Reputation: 453
You cannot send array in the body of requests. They have to be strings and the API that takes this request needs to handle that string. You can convert that list into json then send it. And API needs to convert this json object to array or any other type.
import json
import requests
url = 'your_url'
your_list = ['some', 'list']
data = json.dumps(your_list)
header = {"Authorization": "Token"}
requests.patch(url, data=data, headers=header)
Upvotes: 3