Skyscanner API への http リクエストを介して接続を確立しようとしています。APIからデータを取得するためのアドホックライブラリがPythonにあることは承知していますが、学習目的でhttplib2
.
次のコードを書きました。
import sys
import httplib2
from urllib.parse import urlencode
class Connection(object):
"""Connect to Skyscanner Business API and retrieve quotes"""
API_HOST = "http://partners.api.skyscanner.net"
PRICING_SESSION_URL = "{api_host}/apiservices/pricing/v1.0".format(
api_host=API_HOST)
SESSION_HEADERS = {"Content-Type": "application/x-www-form-urlencode",
"Accept": "application/json"}
def __init__(self, api_key="prtl6749387986743898559646983194", body=None):
"""
:param api_key: the API key, the default is an API key provided for
testing purposes in the Skyscanner API documentation
:param body: the details of the flight we are interested on
"""
if not api_key:
raise ValueError("The API key must be provided")
self.api_key = api_key
self.body = body
self.create_session(api_key=self.api_key, body=self.body)
def get_result(self):
pass
def make_request(self, service_url, method="GET", headers=None, body=None):
"""Perform either a POST or GET request
:param service_url: URL to request
:param method: request method, default is GET
:param headers: request headers
:param data: the body of the request
"""
if "apikey" not in service_url.lower():
body.update({
"apikey": self.api_key
})
h = httplib2.Http(".cache")
response, content = h.request(service_url,
method=method,
body=urlencode(body),
headers=headers)
print(str(response))
def create_session(self, api_key, body):
"""Create the Live Pricing Service session"""
return self.make_request(self.PRICING_SESSION_URL,
method="POST",
headers=self.SESSION_HEADERS,
body=body)
def main():
body = {
"country": "UK",
"currency": "GBP",
"locale": "en-GB",
"originplace": "LOND-sky",
"destinationplace": "NYCA-sky",
"outbounddate": "2016-05-01",
"inbounddate": "2016-05-10",
"adults": 1
}
Connection(body=body)
if __name__ == "__main__":
sys.exit(main())
上記のコードは、Live Pricing セッションを作成するために API に POST リクエストを送信することを行っています。データを取得するには、POST 応答の Location ヘッダーで指定される予約の詳細をポーリングするための URL を含む GET 要求を送信する必要があります。
APIキーは、APIを試すために使用することを提案している一般的なものであるため、ドキュメントで公開されています。
上記のコードを実行すると、次の応答が返されます。
{'content-length': '0', 'date': 'Sun, 24 Apr 2016 08:44:23 GMT', 'status': '415', 'cache-control': 'private'}
ドキュメントには、ステータス 415 が何を表しているかは記載されていません。