Search code examples
pythonpython-3.xapiyelp

How to use Yelp's new API


I am pretty new to programing so I am sure this is not correct but its the best I can do based on my research. Thanks.

import pandas as pd
import numpy as np
import requests
import yelp
requests.get(https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972,headers={'Authorization: Bearer <API KEY that I have>'})

My noob self tells me this is a dictonary

headers={'Authorization: Bearer <API KeY>'}

I know this is prob 100% wrong so I would really love to learn more about using rest API's in Python. I am just doing this as a personal project. My overall goal is to be able to access yelps public data via API. For example, I want to get the reviews for business X.

Update

requests.get("https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972",headers={'Authorization: Bearer <API KEY>'})

I now get the following error

AttributeError: 'set' object has no attribute 'items'

Solution

  • You're definitely not 100% wrong @g_altobelli!

    Let's take the example of getting reviews for business X, where X is one of my favorite restaurants -- la taqueria in San Francisco. Their restaurant id (which can be found in the url of their review page as the last element) is la-taqueria-san-francisco-2.

    Now to our code:

    You have the right idea using requests, I think your parameters might just be slightly off. It's helpful inititally to have some headers. Here's what I added:

    import requests
    
    API_KEY = "<my api key>"
    
    API_HOST = 'https://api.yelp.com'
    BUSINESS_PATH = '/v3/businesses/'
    

    Then I created a function, that took in the business id and returned a jsonified result of the basic data. That looked like this:

    def get_business(business_id):
        business_path = BUSINESS_PATH + business_id
        url = API_HOST + business_path + '/reviews'
        headers = {'Authorization': f"Bearer {API_KEY}"}
    
        response = requests.get(url, headers=headers)
    
        return response.json()
    

    Finally, I called the function with my values and printed the result:

    results = get_business('la-taqueria-san-francisco-2')
    print(results)
    

    The output I got was json, and looked roughly like the following:

    {'reviews': [{'id': 'pD3Yvc4QdUCBISy077smYw', 'url': 'https://www.yelp.com/biz/la-taqueria-san-francisco-2?hrid=pD3Yvc4QdUCBISy077smYw&adjust_creative=hEbqN49-q6Ct_cMosX68Zg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_reviews&utm_source=hEbqN49-q6Ct_cMosX68Zg', 'text': 'My second time here.. \nI love the Burito here it has the distinct taste of freshness.. we order super steak burito and boy it did not disappoint! everything...}

    Does this help? Let me know if you have any more questions.