I've recently been getting a 400 bad request parse error when making a request to my timeline_url.
Im posting to this url timeline_url = 'https://www.googleapis.com/mirror/v1/timeline'
EDIT
Here is the code:
headers = {'Content-Type': 'application/json',
'Authorization' : 'Bearer %s' % access_token}
body = {"text" : "Waddup doe!"}
""" ***********THIS IS RETURNING ERROR 400 PARSE ERROR***********"""
send_request(timeline_url, headers, 'POST',body)
The send_request method is using requests
req = requests.post(url, data=body, headers=headers)
I'm just trying to insert plain text to my timeline.
body_bytes = sys.getsizeof(body)
headers['Content-Length'] = body_bytes
This is inserting an incorrect value into your request headers. sys.getsizeof describes how large the data structure is -- including pointers, counters, etc. It does NOT describe how many bytes the string representation takes on the HTTP stream.
Just delete these lines; requests will fill in Content-Length automatically.
You don't describe how you json-encode the payload. Perhaps you need to do this:
req = requests.post(url, data=json.dumps(body), headers=headers)
See: http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests
Related
First thank you for your time. I'm trying to do an insert using a Rest-API POST, I'm working with Python. Among my messages I have special characters that I want to keep in the destination, which by the way returns an error for them since by default the messages are in UTF-8, but I want them in "ISO-8859-1".
For this I have created the line: headers["Charset"] = "ISO-8859-1" . Python does not give me an error but I continue with the same problem.
The error is:
400 Client Error: Bad Request for url: https://api.example.com/
Here is my code:
import requests
from requests.structures import CaseInsensitiveDict
url = 'https://api.example.com/'
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer "
headers["Content-Type"] = "application/json"
headers["Charset"] = "ISO-8859-1"
collet_x = df_spark.collect()
for row in collet_x:
#insert
resp = requests.post(url, headers=headers, data=row['JSON'])
v_respuesta = resp.text
print(resp.status_code)
print(v_respuesta)
How else can I change the encoding?
From already thank you very much.
Regards
def queue_song(session_id):
song_uri='spotify:track:5RwV8BvLfX5injfqYodke9'
tokens = get_user_tokens(session_id)
headers = {'Content-Type': 'application/json',
'Authorization': "Bearer " + tokens.access_token,
}
url = BASE_URL +'player/queue'
data={
'uri':song_uri
}
response = requests.post(url,headers=headers,data=data).json()
print(response)
Output:
{'error': {'status': 400, 'message': 'Required parameter uri missing'}}
https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue
I dont thing there is any problem with auth tokens... coz 'GET' requests are working fine
By default, using data= in requests.post() sets the content type to application/x-www-form-urlencoded which makes the body a akin to a HTTP form request.
Spotify's API is JSON based, so your data needs to be a valid json data.
You can do it in 2 ways:
response = requests.post(url,headers=headers,data=json.dumps(data)).json()
Or, more simply:
response = requests.post(url,headers=headers,json=data).json()
and in this way you don't need to manually set the application/json header as well.
Edit:
After going through the API docs you linked, there's more wrong with the call you're making.
You're sending the parameters in data - which is the body of the request. But Spotify API specifies the parameters need to be put in the Query i.e. the query string of the URI. Which means your request should be:
response = requests.post(url,headers=headers,params=data).json() # set query string not body
I am trying to post some information into an API based on their recommended format. When I use Postman( tool to test APIs), I see that the response has the isSuccess flag set to true. However, when I write the same code in Python using the requests library, I get the isSuccess flag as false
As mentioned about, I verified the headers and the json data object, both are the same yet the results defer
import requests
data = {"AccountNumber":"100007777",
"ActivityID":"78",
"ActivityDT":"2019-08-07 12:00:00",
"ActivityValue":"1"
}
url = "http://<IP>/<API_PATH>"
headers = {
"X-Tenant":"Default",
"Content-Type":"application/json"
}
response = requests.post(url,data=data, headers = headers)
print(response.content)
This code should successfully post the data and I should get a isSuccess:true in my response variable.
Can anyone help me figure out what might be wrong?
Can you try to change;
response = requests.post(url,data=data, headers = headers)
to;
response = requests.post(url,json=data, headers = headers)
or;
response = requests.post(url,body=data, headers = headers)
I have to use a webservice endpoint that needs both JSON and non-json in the query and I don't know how to do it with the requests package. the same code provided has http.client in it, and I don't have access to that package in this project for unrelated reasons
The example code is:
import http.client
conn=http.client.HTTPSConnection('some.url')
payload="{\"some_json_dict_key\": \"some_json_dict_value\"}"
headers={'content-type': "application/json", 'accept': "application/json"}
conn.request("POST", "/someEndpoint?param1=value_of_param1", payload, headers)
res = conn.getresponse()
data = res.read().decode('utf-8')
The code i have tried which doesnt work:
import requests
headers={'content-type': "application/json", 'accept': "application/json"}
params={'param1': 'value_of_param1'}
json_payload = "{\"some_json_dict_key\": \"some_json_dict_value\"}"
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)
however that doesn't seem to work i get the exception
{'httpMessage': 'Bad Request', 'moreInformation': 'The body of the request, which was expected to be JSON, was invalid, and could not be decoded. The start of an object { or an array [ was expected.'}
According to the documentation:
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
but you're passing a string into the json parameter (I admit that the error message could be clearer). All other parameters are json/dict objects. Make json_payload an actual dictionary.
json_payload = {"some_json_dict_key": "some_json_dict_value"} # real dictionary, not a json string
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)
You must realize that a POST request can pass information in two places: In the body (data) of the request, and in the URL string (the request parameters, like a GET request does). In the example you didn't fully emulate, the parameters are in the URL string, and the body, according to the error message you got back, must consist of a single JSON object. Therefore, use the params dictionary for the URL parameters, like this:
response = requests.post(url, headers=headers, params=params, data=json_payload)
That ought to do it, unless there are other details to take care of.
I'm trying to send a simple post request to a very simple django server and can't wrap my head around why the post data isn't appearing in the requests post dictionary and instead its in the request body.
Client code:
payload = {'test':'test'}
headers = {'Content-type': 'application/json','Accept': 'text/plain'}
url = "localhost:8000"
print json.dumps(payload)
r = requests.post(url,data=json.dumps(payload),headers=headers)
Server Code:
def submit_test(request):
if request.method == 'POST':
print 'Post: "%s"' % request.POST
print 'Body: "%s"' % request.body
return HttpResponse('')
What is printed out on the server is:
Post: "<QueryDict: {}>"
Body: "{"test": "test"}"
I've played around with the headers and sending the data as a straight dictionary and nothing seems to work.
Any ideas? Thanks!!
The POST dictionary only contains the form-encoded data that was sent in the body of the request. The body attribute contains the raw body of the request as a string. Since you are sending json-encoded data it only shows up in the raw body attribute and not in POST.
Check out more info in the docs.
Try form-encoded data and you should see the values in the POST dict as well:
payload = {'test':'test'}
url = "localhost:8000"
requests.post(url, data=payload)
Specifying a user-agent in the headers should enable Django to interpret the raw data of the body and to correctly populate the POST dictionary. The following should work:
payload = {'test': 'test'}
url = "http://localhost:8000"
headers = {'User-Agent': 'Mozilla/5.0'}
requests.post(url, data=payload, headers=headers)
You should remove 'Content-type' from headers and use default one which is 'multipart/form-data'
response = client.post(
'/some_url/',
data={'post_key': 'some_value'},
# content_type='application/json'
)
If you uncomment 'content_type' data will be only in request.body