gpt4 book ai didi

python - 使用 Python 请求验证 Yelp Fusion API

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:52 46 4
gpt4 key购买 nike

根据 Yelp 文档:“要使用访问 token 对 API 调用进行身份验证,请将 Authorization HTTP header 值设置为 Bearer access_token。” https://www.yelp.com/developers/documentation/v3/get_started

我已经使用 requests 获得了 Yelp API 访问 token ,但无法进行身份验证:

>>> 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"}}'

最佳答案

您应该只传递访问 token ,而不是整个响应。请看下面的代码。基本上您可以从中间开始,因为您已经获得了访问 token ,但我建议您重写整个代码以提高可读性。

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'])

关于python - 使用 Python 请求验证 Yelp Fusion API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40729122/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com