使用Python请求验证Yelp Fusion API

时间:2016-11-21 20:51:12

标签: python api python-requests yelp

根据Yelp文档:"要使用访问令牌验证API调用,请将授权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"}}'

1 个答案:

答案 0 :(得分:4)

您应该只传递访问令牌,而不是整个响应。请看下面的代码。 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'])