简体   繁体   中英

Authenticating Yelp Fusion API with Python requests

According to Yelp docs: "To authenticate API calls with the access token, set the Authorization HTTP header value as Bearer access_token." https://www.yelp.com/developers/documentation/v3/get_started

I have gotten a Yelp API access token using requests , but cannot authenticate:

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

You should pass only access token , not the entire response. Please see below code. Basicaly you can start from the middle, as you already got access token, but i would reccomend to rewrite your entire code for better readability.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM