Trying to use Yelp Fusion API to return businesses..
See original GitHub issueHi! I’m using the code from the sample.py document in yelp-fusion but it is not working. I could possibly be running it incorrectly. Do I need to connect it to an HTML file? Here is the sample code with a few alterations:
from __future__ import print_function
import argparse
import json
import pprint
import requests
import sys
import urllib
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
CLIENT_ID = eCsQkjE5leXqyITcHGYhlg
CLIENT_SECRET = REDACTED
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'
DEFAULT_TERM = 'dinner'
DEFAULT_LOCATION = 'San Francisco, CA'
SEARCH_LIMIT = 3
def obtain_bearer_token(host, path):
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
assert eCsQkjE5leXqyITcHGYhlg, #"Please supply your client_id."
assert REDACTED,
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()['r-3EuFhgbS2RAoXvt5yfn7xG1c9shKC7CC0_x2DCvzbtXrIZ5A0aFy4Y7wjqxralz_pW5pxTmXjt21rgFnQjuOWJpzYxWsRhSRiIGHbbm__4k74P232lXevUKFhDWHYx'] # the 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,
}
print(u'Querying {0} ...'.format(url))
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
}
return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
def get_business(bearer_token, business_id):
"""Query the Business API by a business ID.
Args:
business_id (str): The ID of the business to query.
Returns:
dict: The JSON response from the request.
"""
business_path = BUSINESS_PATH + business_id
return request(API_HOST, business_path, bearer_token)
def query_api(term, location):
"""Queries the API by the input values from the user.
Args:
term (str): The search term to query.
location (str): The location of the business to query.
"""
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
response = search(bearer_token, term, location)
businesses = response.get('businesses')
if not businesses:
print(u'No businesses for {0} in {1} found.'.format(term, location))
return
business_id = businesses[0]['id']
print(u'{0} businesses found, querying business info ' \
'for the top result "{1}" ...'.format(
len(businesses), business_id))
response = get_business(bearer_token, business_id)
print(u'Result for business "{0}" found:'.format(business_id))
pprint.pprint(response, indent=2)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--term', dest='term', default=DEFAULT_TERM,
type=str, help='Search term (default: %(default)s)')
parser.add_argument('-l', '--location', dest='location',
default=DEFAULT_LOCATION, type=str,
help='Search location (default: %(default)s)')
input_values = parser.parse_args()
try:
query_api(input_values.term, input_values.location)
except HTTPError as error:
sys.exit(
'Encountered HTTP error {0} on {1}:\n {2}\nAbort program.'.format(
error.code,
error.url,
error.read(),
)
)
if __name__ == '__main__':
main()
Issue Analytics
- State:
- Created 7 years ago
- Comments:10 (5 by maintainers)
Top Results From Across the Web
Getting Started with Yelp Fusion API - Yelp Developer Portal
Let's use a simple scenario to demonstrate how to use the Yelp Fusion API. ... can see that it's returning suggestions for terms,...
Read more >The Complete Guide to the Yelp API - Spectral
Find out all about the Yelp API (Fusion) and how to use it. ... By default, the first 20 businesses are returned based...
Read more >Yelp API to return all reviews for one businesses w/ sample.py
Hi, I am running the sample.py as follow: # -*- coding: utf-8 -*- """ Yelp Fusion API code sample. This program demonstrates the...
Read more >How to get and use Yelp API Key: Fusion API and Business API
This endpoint returns up to 1000 businesses based on the provided search criteria. It has some basic information about the business. Fusion ......
Read more >Yelp Fusion API Profile: Pull Local Business Data - RapidAPI
Using Yelp's Fusion API, you can search local businesses and pull reviews, phone numbers and accepted transaction types (ex. food delivery and ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
That would work, but it might be easier just to supply your input to the
search()
function:Remember, this example is just a starting point — for example, if you’re building a web page that uses this, you should call these functions from your server code, rather than running the
main()
function from the command line.Ah, I see you’ve made some changes to the example that aren’t legal Python. Is this your first time writing Python code?
String data should have quotes around it:
You should only have to change the two lines
You’ve pasted your credentials into several other pieces of the code, breaking them. You shouldn’t need to do that!
I’d suggest starting over, and only changing those two lines — that should work better.