簡體   English   中英

使用Python請求驗證Yelp Fusion API

[英]Authenticating Yelp Fusion API with Python requests

根據Yelp文檔:“要使用訪問令牌驗證API調用,請將Authorization HTTP標頭值設置為Bearer access_token。” https://www.yelp.com/developers/documentation/v3/get_started

我使用requests獲得了Yelp API訪問令牌,但無法進行身份驗證:

>>> data = {"grant_type": "client_credentials", "client_id": "foo", "client_secret": "bar"}
>>> r = requests.post("https://api.yelp.com/oauth2/token", data=data)
>>> r
<Response [200]>
>>> r.text
'{"expires_in": 15550795, "token_type": "Bearer", "access_token": "foobar"}'
>>> params = json.loads(r.text)
>>> url = "https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972&"
>>> test = requests.get(url, params=params)
>>> test.text
'{"error": {"description": "An access token must be supplied in order to use this endpoint.", "code": "TOKEN_MISSING"}}'

您應該只傳遞訪問令牌,而不是整個響應。 請看下面的代碼。 Basicaly你可以從中間開始,因為你已經獲得了訪問令牌,但我建議重寫整個代碼以提高可讀性。

import requests

app_id = 'client_id'
app_secret = 'client_secret'
data = {'grant_type': 'client_credentials',
        'client_id': app_id,
        'client_secret': app_secret}
token = requests.post('https://api.yelp.com/oauth2/token', data=data)
access_token = token.json()['access_token']
url = 'https://api.yelp.com/v3/businesses/search'
headers = {'Authorization': 'bearer %s' % access_token}
params = {'location': 'San Bruno',
          'term': 'Japanese Restaurant',
          'pricing_filter': '1, 2',
          'sort_by': 'rating'
         }

resp = requests.get(url=url, params=params, headers=headers)

import pprint
pprint.pprint(resp.json()['businesses'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM