Git Product home page Git Product logo

yelp-python's Introduction

Build Status Coverage Status

yelp-python

A Python library for the Yelp Fusion API. It simplifies the process of request construction, and response parsing for Python developers. This clientlib is built and tested on Python 2.7 and 3.6.

Please file issues on this repository for bugs/feature requests for this python client. For bugs/features requests for the Yelp Fusion API itself, please open issues on the dedicated Yelp Fusion repository.

Installation

Install yelp-python from PyPI using:

pip install yelp

Usage

Basics

You must have a Yelp Fusion API key to make requests to the API. Sign up for an API key at https://www.yelp.com/developers/v3/manage_app. Instantiate yelp.client.Client with your API key, and start making requests!

from yelp.client import Client

MY_API_KEY = "abcefghijklmnopqrstuvqwxy123456789" #  Replace this with your real API key

client = Client(MY_API_KEY)

Now you can use the client object to make requests.

Business Details Endpoint

Endpoint documentation: https://www.yelp.com/developers/documentation/v3/business

To query the Business Details Endpoint use the busines.get_by_id function with a Yelp business alias (i.e. yelp-san-francisco) or ID (i.e. 4kMBvIEWPxWkWKFN__8SxQ). You can also pass in the locale parameter as specified in the Business Details Endpoint Documentation.

> business_response = client.business.get_by_id('yelp-san-francisco')

> business_response
Business(alias='yelp-san-francisco', attributes=None, categories=[Category(alias='massmedia', title='Mass Media')], coordinates=Coordinates(latitude=37.7867703362929, longitude=-122.399958372115), display_phone='(415) 908-3801', hours=[Hours(hours_type='REGULAR', is_open_now=True, open=[DayHours(day=0, end='1800', is_overnight=False, start='0800'), DayHours(day=1, end='1800', is_overnight=False, start='0800'), DayHours(day=2, end='1800', is_overnight=False, start='0800'), DayHours(day=3, end='1800', is_overnight=False, start='0800'), DayHours(day=4, end='1800', is_overnight=False, start='0800')])], id='4kMBvIEWPxWkWKFN__8SxQ', image_url='https://s3-media2.fl.yelpcdn.com/bphoto/nQK-6_vZMt5n88zsAS94ew/o.jpg', is_claimed=True, is_closed=False, location=Location(address1='140 New Montgomery St', address2='', address3='', city='San Francisco', country='US', cross_streets='Natoma St & Minna St', display_address=['140 New Montgomery St', 'San Francisco, CA 94105'], state='CA', zip_code='94105'), name='Yelp', phone='+14159083801', photos=['https://s3-media2.fl.yelpcdn.com/bphoto/nQK-6_vZMt5n88zsAS94ew/o.jpg', 'https://s3-media2.fl.yelpcdn.com/bphoto/yFHIb9gob4TzhKUemMOPww/o.jpg', 'https://s3-media1.fl.yelpcdn.com/bphoto/EHCfkEpZraIfPl8gvCo1tg/o.jpg'], rating=2.0, review_count=8421, transactions=[], url='https://www.yelp.com/biz/yelp-san-francisco?adjust_creative=wpr6gw4FnptTrk1CeT8POg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm_source=wpr6gw4FnptTrk1CeT8POg')

Contributing

  1. Fork it (http://github.com/yelp/yelp-python/fork)
  2. Setup your virtual environment
$ pip install tox
$ tox -e venv
$ . venv-yelp/bin/activate
  1. Create your feature branch (git checkout -b my-new-feature)
  2. Commit your changes (git commit -am 'Add some feature')
  3. Push to the branch (git push origin my-new-feature)
  4. Create new Pull Request

Testing

Please write tests for any new features. We use pytest + tox so just run tox to run the full test suite. Full py.test documentation here.

yelp-python's People

Contributors

asottile avatar dan98765 avatar dinahshi avatar mittonk avatar virgytam avatar watterso avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yelp-python's Issues

Add raw json response method

Parsing the data into python objects is fine but can hide new fields that may be added to the API overtime.

Providing raw json allows caching of data with additional fields and accessing them again at a later time.

requirements.txt missing mock

Mock isn't part of the standard Python 2.7 install; it should be listed in requirements.txt (or preferably a new requirements-dev.txt).

$ virtualenv venv -p python2.7
$ source venv/bin/activate
$ pip install -r requirements.txt
$ cd yelp/tests/
$ python -m pytest .
================================================================================================== test session starts ===================================================================================================
platform linux2 -- Python 2.7.6, pytest-2.8.1, py-1.4.30, pluggy-0.3.1
rootdir: /nail/home/kmitton/pg/other/yelp-python/yelp/tests, inifile: 
collected 18 items / 2 errors 

oauth1_authenticator_test.py ..
obj/business_response_test.py .
obj/business_test.py .
obj/deal_option_test.py .
obj/deal_test.py .
obj/gift_certificate_option_test.py .
obj/gift_certificate_test.py .
obj/location_test.py ..
obj/rating_test.py .
obj/response_object_test.py ....
obj/review_test.py .
obj/search_response_test.py .
obj/user_test.py .

========================================================================================================= ERRORS =========================================================================================================
____________________________________________________________________________________________ ERROR collecting client_test.py _____________________________________________________________________________________________
client_test.py:3: in <module>
    import mock
E   ImportError: No module named mock
____________________________________________________________________________________________ ERROR collecting errors_test.py _____________________________________________________________________________________________
errors_test.py:2: in <module>
    import mock
E   ImportError: No module named mock
=========================================================================================== 18 passed, 2 error in 0.16 seconds ===========================================================================================

Search API/Unicode Error

Greetings,

I am able to construct an API client OK. However, when I search the Yelp API with
params = { 'term': 'food', 'lang': 'fr' }
client.search('San Francisco', **params)

I get the following error:
TypeError: character mapping must return integer, None or unicode

I am trying to call the API from France. Would my location have anything to do with this error?

Thanks for any tips. I am new to Python and a bit overwhelmed by documentation concerning unicode errors.

search_by_coordinates only returns food results

I have been trying to use search_by_coordinates to find POI around me but it seems that it only returns the same food results no matter what I put in as term. See below

Inputs:

params = {
'term': 'superstore',
'limit': '40',
'radius_filter': '10000'
}
response = client.search_by_coordinates( lat, lng, params )

url generated under sign_request

https://api.yelp.com/v2/search/?ll=51.0454027%2C-114.0565189%2C%7B%27term%27%3A+%27superstore%27%2C+%27limit%27%3A+%2740%27%2C+%27radius_filter%27%3A+%2710000%27%7D&oauth_token=XXXXXXXXXXXXXXXXX&oauth_consumer_key=XXXXXXXXXXXXXXXXXX&oauth_nonce=84599947&oauth_timestamp=1457744867

i'm not sure if term=superstore should go right after search/? and this is not happening here. I'm wondering if API is treating it as empty search term.

Sort out "develop" vs "master" branch

"master" is the default branch.

But, we've also got a "develop" branch.

Not clear which one we should be merging things into, and @watterso thinks #27 was merged only into develop and not master (default)...

README.md Responses section

When getting a business' rating in the first example of the Responses section in the Readme:

>>> response.businesses[0].rating.rating
4.5

Should response.businesses[0].rating.rating be response.businesses[0].rating (is it a typo)? I am using Python 2.7. Thanks for the clarification!

Search can't handle Unicode terms

I'd expect Search to take Unicode objects in Python 2.7:

# -*- coding: utf-8 -*-                                                          
from yelp.client import Client                                                   
from yelp.oauth1_authenticator import Oauth1Authenticator                        

auth = Oauth1Authenticator(...)                                                                                                                                                              
client = Client(auth)                                                           
response = client.search('San Francisco', term=u'aü')                           

It fails:

Traceback (most recent call last):
  File "foo.py", line 19, in <module>
    response = client.search('San Francisco', term=u'aü')
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/endpoint/search.py", line 44, in search
    self.client._make_request(SEARCH_PATH, url_params)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/client.py", line 47, in _make_request
    signed_url = self.authenticator.sign_request(url, url_params)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/oauth1_authenticator.py", line 36, in sign_request
    return oauth_request.to_url()
  File "/nail/home/kmitton/pg/kmitton-bash/virtualenv_run/lib/python2.7/site-packages/oauth2/__init__.py", line 363, in to_url
    urllib.urlencode(query, True), fragment)
  File "/usr/lib64/python2.7/urllib.py", line 1354, in urlencode
    l.append(k + '=' + quote_plus(str(elt)))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 1: ordinal not in range(128)

Workaround: Manually encode as UTF-8 bytestring:

response = client.search('San Francisco', term=u'aü'.encode('utf8'))            

Feels like we should be able to handle Unicode.

'Client' object has no attribute 'business'

Hello,

I try the following python code copied from this site:
from yelp.client import Client

MY_API_KEY = 'xxxx'

client = Client(MY_API_KEY)
business_response = client.business.get_by_id('yelp-san-francisco')

Then, I have the error "'Client' object has no attribute 'business'".
Any idea why the given code doesn't work?
Thanks for your help.

API Search business result is in different order from Yelp web search

Example: 'Super Chicken' at zipcode 22182.

On yelp web search, the top result is a restaurant named 'Super Chicken' located in Vienna VA, 22182 with 311 reviews.

However, through API, the first result is a restaurant named 'Super Chicken' but with location in 4323 Kenilworth Ave', u'Bladensburg, MD 20710 with 20 reviews.

Could you please help me understand why this is the case?

Thanks!

Multi language support does't work.

The following code does't work when the parameter 'lang' changes. Only English results are shown.

import io
import json
from yelp.client import Client
from yelp.oauth1_authenticator import Oauth1Authenticator

with io.open('config_secret.json') as cred:
    creds = json.load(cred)
    auth = Oauth1Authenticator(**creds)
    client = Client(auth)

    params = {
          'lang' : 'cn'
    }
    response = client.get_business('yelp-san-francisco', **params)
    print response.business.name
    print response.business.categories

Error formatting hides the very helpful validator messages

When supplying a too-large limit=40 in #43 , yelp-python printed a stacktrace:

$ python foo.py 
Traceback (most recent call last):
  File "foo.py", line 25, in <module>
    response = client.search_by_coordinates(lat, lng, **params)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/endpoint/search.py", line 118, in search_by_coordinates
    self.client._make_request(SEARCH_PATH, url_params)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/client.py", line 48, in _make_request
    return self._make_connection(signed_url)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/client.py", line 54, in _make_connection
    self._error_handler.raise_error(error)
  File "/nail/home/kmitton/pg/other/yelp-python/yelp/errors.py", line 99, in raise_error
    response
yelp.errors.InvalidParameter

The actual error response was:

{u'error': {u'field': u'limit', u'text': u'One or more parameters are invalid in request', u'description': u'Limit maximum is 20', u'id': u'INVALID_PARAMETER'}}

We should really print more of that error message!

Pre-requisites for "requirements.txt"?

I tried to follow your example on Github but have some very basic questions, coming from a novice background.

I saved the file "requirements.txt" in a directory and then in the terminal tried to run:
pip install -r requirements.txt

The following message was returned:

  Could not find a version that satisfies the requirement auth2==1.0 (from -r requirements.txt (line 1)) (from versions: )

No matching distribution found for auth2==1.0 (from -r requirements.txt (line 1))

What other basic steps would I need to take before running the "pip install" command?

Thanks very much for your help!

Help Constructing API Client

Hi,

I have followed the Yelp-python basics exactly but receive an error after entering

with open('config_secret.json') as cred:
    creds = json.load(cred)
    auth = Oauth1Authenticator(**creds)
    client = Client(auth)

params = {
    'term': 'food',
    'lang': 'fr'
}
>>> client.search('San Francisco', **params)

My terminal spits out
TypeError: character mapping must return integer, None or unicode

My guess is that this has something to do with the unicode of my keys/tokens in my config_secret.json.

What would be the most efficient way to resolve this error? Thanks for your help.

**Note: myconfig_secret.json is not in a .gitignorefile, so I revised io.open() to open().

search the exact restaurant by coordinates

I want to search for the restaurant with the exact coordinates of that restaurant. Because I have data from yelp-academic-dataset. However, I can only get a list. I have tried to set "sort" : 1, 'radius_filter': 0; Then sometimes it returns nothing. I noticed that there is a input named "accuracy", however I can find the explanation for how to set this, basically I want 100% accuracy. Is there any solution?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.