Google QPX Express API with Python

2.6k views Asked by At

Here is the code I write for getting the flight price information by using Google QPX Express API from Python:

import urllib2
import json

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyBH_S3LDUQWmQtbXyExUShtUSI8MmxObfY"
code = {
  "request": {
    "passengers": {
      "kind": "qpxexpress#passengerCounts",
      "adultCount": 1,
    },
    "slice": [
      {
        "kind": "qpxexpress#sliceInput",
        "origin": "DCA",
        "destination": "NYC",
        "date": 2014-11-20,
      }
    ],
    "refundable": False,
    "solutions": 5
  }
}
jsonreq = json.dumps(code, encoding = 'utf-8')
req = urllib2.Request(url, jsonreq, {'Content-Type': 'application/json'})
flight = urllib2.urlopen(req)
response = flight.read()
flight.close()
print(flight)

It always give me the error of urllib2.HTTPError: HTTP Error 400: Bad Request. I really can't figure out what to do.

Related: QPX Express API from Python

1

There are 1 answers

1
Stavros Macrakis On BEST ANSWER

You're almost there! Just a few minor errors:

  • The date needs to be quoted
  • False is written in lowercase in json: false, so you'll need to quote it in Python
  • No commas before close-bracket (OK in Python, but better to follow json conventions)
  • print(response), not print(flight)
  • also, it's generally a bad idea to publish your API key in a forum!

This gives:

import urllib2
import json

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXX"
code = {
  "request": {
    "passengers": {
      "kind": "qpxexpress#passengerCounts",
      "adultCount": 1,
    },
    "slice": [
      {
        "kind": "qpxexpress#sliceInput",
        "origin": "DCA",
        "destination": "NYC",
        "date": "2015-11-20",
      }
    ],
    "refundable": "false",
    "solutions": 5
  }
}
jsonreq = json.dumps(code, encoding = 'utf-8')
req = urllib2.Request(url, jsonreq, {'Content-Type': 'application/json'})
flight = urllib2.urlopen(req)
response = flight.read()
flight.close()
print(response)

By the way, to get the best responses, you should probably ask for more than 5 solutions. QPX Express tries to return a variety of answers (e.g., different times, different airlines, etc.) so if you want to have your own selection of the best trade-off of qualities, you probably want to examine more solutions.