使用Python的Google QPX Express API

时间:2014-11-12 01:43:33

标签: api python-2.7 google-api urllib2 http-error

以下是我使用Python的Google QPX Express API获取航班价格信息的代码:

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)

它总是给我urllib2.HTTPError: HTTP Error 400: Bad Request的错误。我真的无法弄明白该怎么做。

相关:QPX Express API from Python

1 个答案:

答案 0 :(得分:4)

你快到了!只是一些小错误:

  • 需要引用日期
  • False在json:false中以小写字母书写,因此您需要在Python中引用它
  • 在close-bracket之前没有逗号(在Python中可以,但最好遵循json约定)
  • 打印(响应),不打印(飞行)
  • 此外,在论坛中发布API密钥通常是一个坏主意!

这给出了:

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)

顺便说一下,为了得到最好的回答,你应该要求超过5个解决方案。 QPX Express尝试返回各种答案(例如,不同的时间,不同的航空公司等),因此如果您想要自己选择最佳的质量权衡,您可能希望检查更多的解决方案。