2016-10-29 23 views
2

我是使用API​​和Python獲取數據的新手。我想從我的交易平臺提取數據。他們所提供的以下說明:使用Python訪問交易平臺的API

http://www.questrade.com/api/documentation/getting-started

我確定了步驟4,有一個訪問令牌。我需要第5步的幫助。如何翻譯此請求:

GET /v1/accounts HTTP/1.1 
Host: https://api01.iq.questrade.com 
Authorization: Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp 

into Python code?我試過

import requests 
r = requests.get('https://api01.iq.questrade.com/v1/accounts', headers={'Authorization': 'access_token myToken'}) 

我想,看完這個:python request with authentication (access_token)

任何幫助,將不勝感激。謝謝。

+1

'headers = {'Authorization':'Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp'}' –

+0

似乎不起作用。獲取<響應[401]> – tpoh

+0

你應該在你的真實訪問令牌中替換上面例子中的「承載者」之後的那個令牌。但是,這是預期的標題格式。 '401'錯誤是未經授權的,這意味着令牌無效。 –

回答

1

正如你所指出的,第4步後,你應該已經收到了訪問令牌如下:

{ 
    「access_token」: 」C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp」, 
    「token_type」: 」Bearer」, 
    「expires_in」: 300, 
    「refresh_token」: 」aSBe7wAAdx88QTbwut0tiu3SYic3ox8F」, 
    「api_server」: 」https://api01.iq.questrade.com」 
} 

爲了讓後續的API調用,您需要來構建你的URI如下:

uri = [api_server]/v1/[rest_operation] 

e.g. 
uri = "https://api01.iq.questrade.com/v1/time" 

Note: Make sure you use the same [api_server] that you received in your json object from step 4, otherwise your calls will not work with the given access_token 

接下來,構建你的標題如下:

headers = {'Authorization': [token_type] + ' ' + [access_token]} 

e.g. 
headers = {'Authorization': 'Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp'} 

最後,請您致電請求作爲弗洛ws

r = requests.get(uri, headers=headers) 
response = r.json() 

希望這會有所幫助!

注意:您可以在GitHub上找到一個Questrade API Python包裝器,它可以爲您處理上述所有問題。 https://github.com/pcinat/QuestradeAPI_PythonWrapper