Skip to content

Instantly share code, notes, and snippets.

@Code-Egg
Created November 10, 2019 13:43
Show Gist options
  • Save Code-Egg/80125648021df66164eded7fec938e93 to your computer and use it in GitHub Desktop.
Save Code-Egg/80125648021df66164eded7fec938e93 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import pprint
import requests
import sys
try:
# For Python 3.0 and later
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode
except ImportError:
# Fall back to Python 2's urllib2 and urllib
from urllib2 import HTTPError
from urllib import quote
from urllib import urlencode
# OAuth credential placeholders that must be filled in by users.
# You can find them on
# https://www.yelp.com/developers/v3/manage_app
CLIENT_ID = 'xxxxxxxxx'
CLIENT_SECRET = 'xxxxxxxxx'
# API constants, you shouldn't have to change these.
API_HOST = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/' # Business ID will come after slash.
TOKEN_PATH = '/oauth2/token'
GRANT_TYPE = 'client_credentials'
# Defaults for our simple example.
DEFAULT_TERM = 'restaurant'
DEFAULT_LOCATION = 'No. 1, Section 4, Roosevelt Rd, Da’an District, Taipei City, Taiwan 10617'
SEARCH_LIMIT = 5
def obtain_bearer_token(host, path):
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
assert CLIENT_ID, "Please supply your client_id."
assert CLIENT_SECRET, "Please supply your client_secret."
data = urlencode({
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': GRANT_TYPE,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
response = requests.request('POST', url, data=data, headers=headers)
bearer_token = response.json()['access_token']
return bearer_token
def request(host, path, bearer_token, url_params=None):
url_params = url_params or {}
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
headers = {
'Authorization': 'Bearer %s' % bearer_token,
}
response = requests.request('GET', url, headers=headers, params=url_params)
return response.json()
def search(bearer_token, term, location):
url_params = {
'term': term.replace(' ', '+'),
'location': location.replace(' ', '+'),
'limit': SEARCH_LIMIT,
'radius': 1000
}
return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
def get_restaurant(term, location):
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
response = search(bearer_token, term, location)
businesses = response.get('businesses')
restaurants = []
for business in businesses:
restaurant = {}
restaurant['name'] = business['name']
restaurant['address'] = business['location']['display_address'][0]
restaurant['photo'] = business['image_url']
restaurant['yelp_url'] = business['url']
restaurants.append(restaurant)
return restaurants
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment