Yelp Fusion API is a REST API that gives access to information across 50 million businesses across countries.
In this tutorial, you will be learning how to use the Yelp API to search businesses by providing their names, locations or phone numbers. You will also learn to match businesses in a given location to check their availability. You will be using the requests library of Python, Requests and JSON library to parse the JSON response of data.
This tutorial covers the following features of the Yelp API: Business Search, Reviews Search, Phone Search, and Business Match.
Finally, there will be a practical project to help you use Yelp API in a real-life case.
Generate Yelp API Key
The Yelp Fusion API uses private key authentication to authenticate all endpoints. You have create an app on Yelp to generate your private API Key.
1. Sign up at: https://www.yelp.com/signup
2. Go to the “Manage App” tab and then click “Create App”. Fill in the form and click “Create New App”.
3. You can see the API Key you need has been automatically generated.
Import Libraries
Import Requests and JSON libraries to accomplish the task. Use Python’s Requests library to make GET requests to the API, and the JSON library to parse the data received as a response from the API.
1 2 3 |
import requests import json |
Replace the value of the variable api_key with your own API key. Then, create a headers dictionary to pass the API key into the request that you will make to the API.
1 2 3 |
api_key='copy_your_api_key_here' headers = {'Authorization': 'Bearer %s' % api_key} |
Business Search
You can search for businesses using a search term (e.g. “seafood”) and you must specify the location of the businesses you are searching for. You need to pass the parameters in a dictionary.
1 2 3 4 5 |
url='https://api.yelp.com/v3/businesses/search' # In the dictionary, term can take values like food, cafes or businesses like McDonalds params = {'term':'seafood','location':'New York City'} |
When you make a GET request to the API, the status code of the request is searched. If it is 200, only then the JSON response will contain results from the API.
1 2 3 4 5 6 |
# Making a get request to the API req=requests.get(url, params=params, headers=headers) # proceed only if the status code is 200 print('The status code is {}'.format(req.status_code)) |
1 2 3 |
# printing the text from the response json.loads(req.text) |
You will get a result similar to this.
In the practical project, you will see how to extract data from this JSON response.
Business Reviews
Among the endpoints offered by the Yelp API is “reviews”. You need to know the ID of the business to be able to extract its reviews. To clarify this, let’s use this id “FEVQpbOPOwAPNIgO7D3xxw” for example.
1 2 3 4 |
url = "https://api.yelp.com/v3/businesses/FEVQpbOPOwAPNIgO7D3xxw/reviews" req = requests.get(url, headers=headers) print('the status code is {}'.format(req.status_code)) |
When we print the result, Yelp gives you 3 reviews.
1 2 |
json.loads(req.text) |
Phone Search
You can also extract business details using the phone number of the business.
1 2 |
url='https://api.yelp.com/v3/businesses/search/phone' |
You should pass the phone number in your params dictionary as you can see here:
1 2 |
params = {'phone':'+14159083801'} |
1 2 3 4 |
req = requests.get(url, params=params, headers=headers) print('The status code is {}'.format(req.status_code)) json.loads(req.text) |
Business Match
Similarly, you can match businesses by giving the name of a business and its address as you can see in this example:
1 2 3 4 5 6 7 8 9 10 11 12 |
url='https://api.yelp.com/v3/businesses/matches' params={'name':"starbucks","address1": "758 N Point St", "address2": "", "address3": "", "city": "San Francisco", "state": "CA", "zip_code": "94109", "country": "US"} req = requests.get(url, headers=headers, params=params) print('The status code is {}'.format(req.status_code)) print(req.text) |
Project: Extract Bookstores in New York City, Details & Reviews
First of all, import the Python libraries, Requests and JSON.
1 2 3 |
import requests import json |
Then, use your API Key.
1 2 3 |
api_key = 'copy_your_api_key_here' headers = {'Authorization': 'Bearer %s' % api_key} |
Search Using Term and Location
Now, use the Business Search URL and specify the search “term” and the “location”. Here we are searching for bookstores in New York City.
1 2 3 |
url='https://api.yelp.com/v3/businesses/search' params={'term':'bookstore', 'location':'New York City'} |
Send a request.
1 2 |
req = requests.get(url, params=params, headers=headers) |
Convert the data into a JSON object.
1 2 |
parsed = json.loads(req.text) |
Now, you can print parsed to get an idea how it looks like.
1 2 |
print(json.dumps(parsed, indent=4)) |
Parse Businesses in JSON Response
As you can see in the output, “businesses” is a list, enclosed by a square brackets.
{
“businesses”: [
{
“id”: “ehUuSk5gPTCQmwS_ubgKRA”,
….
]
So you have to extract businesses first into a Python list and then loop over the businesses in the list.
1 2 3 4 5 6 7 8 9 |
businesses = parsed["businesses"] for business in businesses: print("Name:", business["name"]) print("Rating:", business["rating"]) print("Address:", " ".join(business["location"]["display_address"])) print("Phone:", business["phone"]) print("\n") |
Note that the “display_address” is inside another dictionary; so you have to access “location” first and then “display_address”. Note also that the “display_address” is a list; so you have to use the join() method to merge it into one string.
“location”: {
“address1”: “139 Chrystie St”,
“address2”: null,
“address3”: “”,
“city”: “New York”,
“zip_code”: “10002”,
“country”: “US”,
“state”: “NY”,
“display_address”: [
“139 Chrystie St”,
“New York, NY 10002
]
}
When you run the code, you will get an output similar to this:
Name: The Mysterious Bookshop
Rating: 4.5
Address: 58 Warren St New York, NY 10007
Phone: +12125871011
Name: Human Relations
Rating: 5.0
Address: 1067 Flushing Ave Brooklyn, NY 11237
Phone:
Name: Astoria Bookshop
Rating: 4.5
Address: 31-29 31st St Astoria, NY 11102
Phone: +17182782665
Extract Business Reviews
Now, lets also extract the ID of each business to search for its reviews using the Business Reviews endpoint. Note you are still inside the for loop.
1 2 |
id = business["id"] |
Then, apply the same steps to connect to the API. For the reviews endpoint, you will have to concatenate the URL with the id you have just extracted.
1 2 3 4 |
url = "https://api.yelp.com/v3/businesses/" + id + "/reviews" req = requests.get(url, headers=headers) parsed = json.loads(req.text) |
You can print parsed to get an idea how it looks like.
1 2 |
print(json.dumps(parsed, indent=4)) |
Also, the reviews are inside a list; so you will have to extract the list first.
1 2 |
reviews = parsed["reviews"] |
Now, loop over the reviews to extract the name of the user, the rating, and the review text. Note that the name is inside another dictionary.
‘user’: {‘id’: ‘8YkvYzOIT-8pKIQNS1j_rg’,
‘profile_url’: ‘https://www.yelp.com/user_details?userid=8YkvYzOIT-8pKIQNS1j_rg’,
‘image_url’: ‘https://s3-media4.fl.yelpcdn.com/photo/_qRYsM-o-5u3_TL2Q0lZnQ/o.jpg’,
‘name’: ‘Alvin W.’}
So you have to access “user” first and then “name”.
1 2 3 |
for review in reviews: print("User:", review["user"]["name"], "Rating:", review["rating"], "Review:", review["text"], "\n") |
Project Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import requests import json api_key = 'copy_your_yelp_api_key_here' headers = {'Authorization': 'Bearer %s' % api_key} url = 'https://api.yelp.com/v3/businesses/search' params = {'term':'bookstore','location':'New York City'} req = requests.get(url, params=params, headers=headers) parsed = json.loads(req.text) businesses = parsed["businesses"] for business in businesses: print("Name:", business["name"]) print("Rating:", business["rating"]) print("Address:", " ".join(business["location"]["display_address"])) print("Phone:", business["phone"]) print("\n") id = business["id"] url="https://api.yelp.com/v3/businesses/" + id + "/reviews" req = requests.get(url, headers=headers) parsed = json.loads(req.text) reviews = parsed["reviews"] print("--- Reviews ---") for review in reviews: print("User:", review["user"]["name"], "Rating:", review["rating"], "Review:", review["text"], "\n") |
HI, Nice tutorial. The question I have is. How do you make a request for more than 1000 businesses from Yelp API
Hi Kelvin! Do you mean via the Business Search endpoint? If so, you can put them into a list and loop on it.
Hi,
can you please let me know if i want to validate yelp id so how can i do this ?
like i want to send in request yelp id and i want to get response if exists all information if not exists then it will return invalid yelp id or something else.
Hi Subhash! What about putting your code portion inside “try, except”. Under “except”, you can send the error message you prefer.
Thanks, this tutorial made things easy.
Question: when I run the code you provided for, say Business Search, at the very bottom of the json.loads(req.text) output it says ‘total: 11800’. Do you know what this means? I figured it would be the number of businesses matching the parameters, but when I inspect the text manually, there are maybe only 20-50 businesses.
Thanks again!
Nathan, the API does not allow more than 50 per request. You need to use the
offset
parameter to get the next page of results. For using offset, give it any number. If you havelimit=50
, that means you are getting results 1-50, so give itoffset=51
and you will get 51-100. Check here for more details.Again, the API can only return up to 1,000 results at this time.
can i used this code to extract the information of users????
@aftab – You can find all the available endpoints here.