I use a library requests:
import requests
r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))
How to display body and headers before sending POST request? or display full request how it is sent?
Because server returns 400 HTTP with message Bad Request. So I need to see what is sending.
When I do:
print r.request.body
It returns:
subcategory_id=1378&category_id=45&features=id&features=value&features=id&features=value&features=id&features=value&offer_type=18979
But body is:
data = {
'category_id': category_id,
'subcategory_id': subcategory_id,
'offer_type': offer_type,
'features': [
{"id": "7", "value": "12900"},
{"id": "12", "value": "Title adadadadasdasdadad"},
{"id": "16", "value": ["3360383821"]}
]
}
How is it possible?
r.request is the corresponding Request object you need.
import requests
r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))
print r.request.headers
print r.request.body
You can do it after you get the response, everything will still be there. See PreparedRequest.
As for your edited question, use requests.post(url=url, json=data, ...).
r.url
r.headers
r.body
should work in the terminal, probably have to print it in a script
You also don't need "url=url", you can just leave it as "url", assuming that's where you've stored the base you're trying to post to.
You can use portal httpbin.org for test. It sends back all your data.
Related
I am trying to send a POST request to Itunes reporter API to download a sales report: https://help.apple.com/itc/appsreporterguide/#/apd68da36164
In the queryInput, I pass in "1234" which is the vendorId.
import requests
headers = { "access_token": "123"}
json_data = {
"version": "1.0",
"mode": "Test",
"queryInput": "[p=Reporter.properties, Sales.getReport, 1234, Sales, Summary, Daily, 20230101]"
}
response = requests.post('https://reportingitc-reporter.apple.com/reportservice/sales/v1',
headers=headers, json=json_data)
#content = response.json()
print(response.content, response.status_code)
However, looks like the way I am passing parameters is incorrect because I only get this as the response:
b'' 400
I am certain that the access token is correct but not sure if i am passing it correctly.
I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy
How I can use this JSON Data on POST
{"data":"{\"email\":\"anything65#gmail.com\",\"agreedToTerms\":true,\"profile\":{\"profileTypeID\":1,\"agreedToTerms\":true,\"firstName\":\"name\",\"lastName\":\"dfghjefws\",\"errors\":{}}}"}
This is My currently code, I got every time "message: Server Error"
data_profile2 = {"data":"{\"email\":\"anything65#gmail.com\",\"agreedToTerms\":true,\"profile\":{\"profileTypeID\":2,\"agreedToTerms\":true,\"firstName\":\"name\",\"lastName\":\"dfgh jefws\",\"errors\":{}}}"}
reqeust_1 = session.post(url_profile,headers=headers_profile, json=data_profile2)
requests doc
POST request
import requests
payload= {"data": {"email": "anything65#gmail.com", "agreedToTerms": True , "profile": {"profileTypeID": 1,"agreedToTerms": True, "firstName": "name", "lastName": "dfghjefws", "errors": {}}}}
request_1 = requests.get(url_profile, headers=headers_profile, data=payload)
update
If you use json=payload, your Content-Type in header will be application/json automatically.
I assume that a session is not mandatory for that you want to do. Sessions persist parameters across many requests.
I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.
I am trying to use Google's QPX Express API from python. I keep running into a pair of issues in sending the request. At first what I tried is this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
based upon the code from: urllib2 and json
When I run the above code I get the following error message:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
I searched for a solution and adapted my code based upon the following question: TypeError: POST data should be bytes or an iterable of bytes. It cannot be str
I changed my code to this:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)
However, when I run this code I get the following error message:
urllib.error.HTTPError: HTTP Error 400: Bad Request
I also tried changing utf-8 to ascii but I was unsuccessful. How can I get this working properly?
Here is a solution using the excelent requests library.
import json
import requests
api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}
params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}
response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data
I am not sure why you request is not working. Maybe it is really the request parameters that were wrong. The date definitely needs to be in the future!
False needs to be in lowercase in JSON, so you need to quote it in Python, like this "refundable" : "false". Otherwise, your query looks good (obviously you'll need to update the date). By the way, it isn't good practice to include your API key in a public forum.