QPX Express API from Python - python

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.

Related

send post request to itunes Reporter

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.

Post Bad Request rest api in python

I am attempting to post some data through REST API in Python.
data.json
{
"LastModifiedAt": "2020-12-21T20:19:45.335Z",
...
...
}
I am using following code to POST the data.
with open('data.json') as fh:
data = json.load(fh)
headers = {
'Content-Type': 'application/json',
'X-API-Key':'ABC=='
}
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,data=data)
I always get following as response status_code = 400
{
"ModelState": {
"line": [
"Unexpected character encountered while parsing value: L. Path '', line 0, position 0."
]
},
"Message": "The request is invalid."
}
How do I debug this? My URL is correct according to API documentation. Why does it return "Bad Request" status code?
I replaced data with json and it worked.
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,json=data)
I used Postman as suggested by AndroidDev to debug this.

How can I find the data parameters required for a requests.post function with a specific URL?

I would like to use the requests library to make a request to a particular webpage, http://latex2png.com/api/convert, in order to convert some latex to a PNG image. However, I am unsure of what data parameters the website accepts.
Is there any way to use the requests library to see which parameters need to be fulfilled?
I've tried running
options = {
"auth": {"user": "guest", "password": "guest"},
"latex": '$a^3$',
"resolution": 900,
"color": "969696",
}
r = requests.post('http://latex2png.com/api/convert')
print(r.content)
but I get b'{"result-message":"no request","result-code":-2}'.
There is no documentation or help online with this specific API and website.
That's because the way you post is wrong, try this:
import requests
headers = {
"Content-type": "application/x-www-form-urlencoded",
}
data = {
"auth": {
"user": "guest",
"password": "guest"
},
"latex": "a^3",
"resolution": 600,
"color": "969696"
}
r = requests.post('http://latex2png.com/api/convert', headers=headers, json=data) # the right way to send POST requests
print(r.json()) # print the json
image_url = "http://latex2png.com" + r.json()['url']
r = requests.get(image_url)
with open("download.png", "wb+") as f: # download it.
f.write(r.content)

Unsupported Media type error for request.post

I am working on a api call with python. Here I have the parameters in json format that was generated in the website I am trying to access. But when I try to run the program I get an 415: unsupported Media Type error. Not sure what I am doing wrong, as I am using the parameters generated by the website.
this is my code so far
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": "false"
}
}
response = requests.post(url, params=parameters)
jprint(response.json())
In the above code, I have removed the actual parameters and replaced them with dummy text. But when I try them with the actual parameters I get the following error
{
"status": 415,
"title": "Unsupported Media Type",
"traceId": "|df46105a-49e1b43f80675626.",
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13"
}
One thing I changed was this code "ForceRefreshAccessToken": "false". In the generated json code, the false was not inside quotes
Not sure what I am doing wrong. Please help me.
import requests
import json
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
url = 'https://einv-apisandbox.nic.in/gstvital/api/auth'
parameters = {
"header": {
"ClientID": "TheClientIDGoesHere",
"ClientSecret": "TheClientSecretGoesHere"
},
"data": {
"UserName": "Username",
"Password": "Password",
"AppKey": "AppKey",
"ForceRefreshAccessToken": False
}
}
hdr = {"Content-Type": "application/json"}
response = requests.post(url, data=parameters, headers=hdr)
print(response.status_code)
print(response.json())
Error 415 indicates that the media type is not supported by the site. This can be fixed by explicitly stating in the header that the content-type will be JSON.
hdr = {"Content-Type": "application/json"} The response code from the site is "200:OK", therefore your request works.

Can not parse JSON share document.\nRequest body:\n\nError:\nnull

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.

Categories

Resources