Everyone!
I'm trying to request from an API in python like so:
headers = {"Content-Type": "application/json", "user-key": self.api_key}
params = {self.filter_fields: '*', self.filter_date: self.date_millis, self.limit: '2'}
request = requests.get(self.api_endpoint, headers=headers, params=params)
I double checked and see no problem with my filters nor api key. The problem is that when the I print the request content "print(request.json())" I get this following error:
{'Err': {'status': 400, 'message': "Invalid content encoding please change 'Content-Type' header."}}
The code performs a GET request. It specifies that the content type is JSON, however, there is no JSON content being passed in the body of the request.
Try omitting the content-type header.
Another possibility is to pass the parameters using the json parameter. The content-type does not need to be set in the headers, requests will send it automatically:
headers = {"user-key": self.api_key}
params = {self.filter_fields: '*', self.filter_date: self.date_millis, self.limit: '2'}
response = requests.get(self.api_endpoint, headers=headers, json=params)
Related
I'm having a problem with a Python request, where I pass the body url to the API data.
Note: I have a Node.js project with TypeScript that works normally, prints to the screen and returns values. However if I try to make a request in Python it doesn't work with an error 401.
Below is an example of how the request is made in Python. can you help me?
import requests
url = 'https://admins.exemple'
bodyData = {
'login': 'admins',
'pass': 'admin',
'id': '26' }
headers = {'Content-Type': 'application/json'}
resp = requests.post(url, headers=headers, data=bodyData)
data = resp.status_code
print(data)
Please dump a dict to a json string as follows:
import json
resp = requests.post(url, headers=headers, data=json.dumps(bodyData))
You also can pass your dict to json kwarg
resp = requests.post(url, headers=headers, json=bodyData)
It will set Content-Type: application/json and dump dict to json automatically
You are not correctly authenticating with the server. Usually, you need to send the username and password to a "sign in" route which will then return a token. Then you pass the token with other requests to get authorization. Since I don't know any details about your server and API, I can't provide any more details to help you out.
I've been trying to use an api on a website for awhile now and the responses from the api return the data in xml. I want the response to be in JSON format, but when I try adding a header into the http request, it keeps sending the response in xml.
I've tried the following code:
import requests
param_list = {'key1': 'value1'}
headers = {'Content-Type': 'application/json'}
url = 'api url'
response = requests.get(url=url, params=param_list, headers=headers,)
print(response.text)
print(response.headers)
The second print statement shows that the 'Content-Type' header returns "text/html"
Any idea on how to fix this? Thanks for your time and help!
I am trying to make a request for a form-data type. The request worked previously when it was just two files being used for the request. However, now an ID has to be inputted in the request also, and it won't work.
I have tried lots of different options of trying to get this to work, the ID is an input in a separate file, same as 'file_a' and 'file_b'. However, it is erroring with the ID form data field.
url = url
headers = {"Authorization": Access_token}
files = [('file_a', open(file_a, 'rb')), ('file_b', open(file_b, 'rb')), ('ID', ID)]
response = requests.post(url=url, files=files, headers=headers)
print(response.content)
I am expecting a response json string, however getting no response as the request is not working due to the ID integer field.
From your code sample, it seems ID is a file, but you probably want to pass it as form-encoded data to data argument in requests.post.
To do this create a dictionary containing the name of the field and its value:
url = url
headers = {"Authorization": Access_token}
files = [('file_a', open(file_a, 'rb')), ('file_b', open(file_b, 'rb'))]
data = {'ID', ID} # here's ID value
response = requests.post(url=url, files=files, headers=headers)
print('status code:', response.status_code)
Here you can find the documentation you need to send form data.
Please, let me know whether this helps you or if you need further help.
I tried to send file with some headers like:
files = {'file': (file, open(file, 'rb'), {'Content-type': 'multipart/form-data; boundary=---BOUNDARY', 'Authorization' : 'Basic ' + api_key})}
r = requests.post(base_url, files=files)
Server returned 401 error that means absent header Authorization. But I sent it
For Basic Authentication you can follow the requests docs. It's visible on the very first line of code in the example on that page.
Use the auth keyword argument to supply a 2-tuple of username and password:
response = requests.post(base_url, files=files, auth=('username', 'password'))
Edit:
If you want to send actual headers, rather than things like Basic Auth, you can do that with the headers keyword argument. This allows you to give a dict of headers you would like to send. For example:
headers = {'Content-Type': 'application/json'}\
response = requests.post(url, data=data, headers=headers)
The auth argument, should be a simplification of the above because Basic Auth is so common, but don't quote me on that one.
You can follow this example to take it from the official documentation I think you should try it first in postman, with the json then and do it from python.
This information is taken from the official documentation
python
I'm trying to send an array(list) of requests to the WheniWork API using requests.post, and I keep getting one of two errors. When I send the list as a list, I get an unpacking error, and when I send it as a string, I get an error asking me to submit an array. I think it has something to do with how requests handles lists. Here are the examples:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data=[{'url': '/rest/shifts', 'params': {'user_id': 0,'other_stuff':'value'}, 'method':'post',{'url': '/rest/shifts', 'params': {'user_id': 1,'other_stuff':'value'}, 'method':'post'}]
r = requests.post(url, headers=headers,data=data)
print r.text
# ValueError: too many values to unpack
Simply wrapping the value for data in quotes:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data="[]" #removed the data here to emphasize that the only change is the quotes
r = requests.post(url, headers=headers,data=data)
print r.text
#{"error":"Please include an array of requests to make.","code":5000}
You want to pass in JSON encoded data. See the API documentation:
Remember — All post bodies must be JSON encoded data (no form data).
The requests library makes this trivially easy:
headers = {"W-Token": "Ilovemyboss"}
data = [
{
'url': '/rest/shifts',
'params': {'user_id': 0, 'other_stuff': 'value'},
'method': 'post',
},
{
'url': '/rest/shifts',
'params': {'user_id': 1,'other_stuff': 'value'},
'method':'post',
},
]
requests.post(url, json=data, headers=headers)
By using the json keyword argument the data is encoded to JSON for you, and the Content-Type header is set to application/json.
Well, It turns out that all I needed to do was add these headers:
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
and then call requests
requests.post(url,data=json.dumps(payload), headers=headers)
and now i'm good!
Always remember when sending an array(list) or dictionary in the HTTP POST request, do use json argument in the post function and set its value to your array(list)/dictionary.
In your case it will be like:
r = requests.post(url, headers=headers, json=data)
Note: POST requests implicitly convert parameter's content type for body to application/json.
For a quick intro read API-Integration-In-Python
I have a similar case but totally different solution,
I've copied a snippet of code which looks like that:
resp_status, resp_data = requests.post(url, headers=headers, json=payload, verify=False)
and this resulted in error:
ValueError: too many values to unpack (expected 2)
just assigning to one variable resolve the issue:
response = requests.post(url, headers=headers, json=payload, verify=False)