Does Airbnb Provide an API?
In this blog post, we continue our exploration of the Mashvisor API. In the earlier post, we have used Mashvisor API to build an app for the Airbnb listing search using Vue.js. But if you explore the Mashvisor API in detail, you realize that it offers much more capabilities for gathering information related to real estate, especially for Airbnb.
Apart from the usual search and price comparison results, Mashvisor API also provides Airbnb trends. This data is attractive in terms of analyzing the real-estate market sentiments and demand-supply equilibrium. So for this tutorial, we are going to look at some of the features of Mashvisor API that can provide valuable stats. We will build a demo script in Python that makes a pretty bar chart to display the Airbnb listing stats for a state in the US.
How to get access to the Airbnb API?
If you are new to Mashvisor Airbnb API, follow the steps below to get access to the API console. Then we head straight to exploring the trends data offered by the API.
1. Sign up for RapidAPI Account
To begin using the Mashvisor API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Subscribe to Mashvisor API
Once signed in, log in to your RapidAPI account. You can either search with the query “Mashvisor API,” or you can directly access the API console here.
Once inside the API console, click on the “Pricing” tab to access the pricing plan. To try this API, you can opt for the Basic subscription, which gives you access to 100 free API calls per month.
3. Check out the API Endpoints under Trends Category
You can get the list of all the API endpoints on the left panel. Scroll down to expand the endpoints under the Trends category.
Select the “GET Top Airbnb Cities” endpoint, and a list of parameters for the API call are displayed.
The ‘state’ is a mandatory parameter that accepts the postal code of a state in the United States. The ‘page’ and ‘items’ are optional, and they specify the pagination for the API result. Their default values are as per the displayed values.
Now, if you trigger this API with the ‘state’ parameter set to CA, which stands for California, then here is what you get.
{ "status": "success", "content": { "input": { "page": 1, "items": 5, "state": "CA" }, "total_page_results": 5, "cities": [ { "city": "Oakland", "state": "CA", "occupancy": 64.73347761, "total_listing": 10624, "occ_listing": 687728.46613926 }, { "city": "San Francisco", "state": "CA", "occupancy": 68.65479425, "total_listing": 9307, "occ_listing": 638970.17010336 }, { "city": "Los Angeles", "state": "CA", "occupancy": 66.97801957, "total_listing": 8024, "occ_listing": 537431.62898956 }, { "city": "San Diego", "state": "CA", "occupancy": 57.78521074, "total_listing": 7145, "occ_listing": 412875.33075874 }, { "city": "Long Beach", "state": "CA", "occupancy": 66.08583922, "total_listing": 4936, "occ_listing": 326199.70236524 } ] } }
The API response contains the top five cities in California with their listing data. The most prominent data points provided by the API are “occupancy” and “total_listing.” The “occupancy” indicates the percentage of properties that are currently occupied, whereas “total_listing” contains the count of all listings in that city.
You can also explore the other API endpoints under the Trends category. The “Get Location Heatmap” is an interesting one as it gives you listing data with geographical bounds that can be superimposed on a map.
Let’s set our focus on the “GET Top Airbnb Cities” and see how we can consume this data in the form of a cool visualization using Python.
Build an Airbnb Listing Bar Chart using Python and Matplotlib
Matplotlib is, by far, the most popular data visualization library in Python. Given the preferential treatment that Python enjoys for data analytics, Matplotlib is an ideal companion for Python data analytics experiments.
Through the Mashvisor API’s “GET Top Airbnb Cities” endpoint, we are going to show you how you can readily consume the API response data by building a bar chart that displays trend data. So if you have the Airbnb listing data about the top ten cities in California, here is how you can visualize it with a cool bar chart.
If you are curious about how this data looks like for the other states, then you can quickly code a python script to generate this chart for you.
Launch your favorite code editor and create a new python file named airbnb_total_listing_chart.py.
Follow along the step below to add code to the python file.
Before you start, make sure that you have the prerequisites set up on your computer for the development environment.
- Python 3 Runtime: You must have a Python 3 runtime installed.
- Matplotlib: You need the matplotlib library for plotting the bar chart. Install it via the pip utility, pip install matplotlib.
- Pandas: Pandas is a data analysis library in Python. It augurs well with matplotlib for cleansing and arranging data in data frames that can be imported into Matplotlib. Install is using the command pip install pandas.
- Requests library: You must have the requests library installed on your Python 3 runtime. This is required for making the API call. You can install it with the command pip install requests.
1. Define the imports and globals
To begin with, you have to import the libraries that are used in the script. The script also uses the RapidAPI key to invoke the Mashvisor API. A global variable is defined to contain the key and the API host.
import matplotlib.pyplot as plt import pandas as pd import requests import json RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>" RAPIDAPI_HOST = "mashvisor-api.p.rapidapi.com"
Make sure to replace the placeholder <YOUR_RAPIDAPI_KEY> with your RapidAPI subscription key.
2. Define a function for triggering Mashvisor API
Every Time the script runs, it makes a call to the “GET Top Airbnb Cities” endpoint of Mashvisor API. Let’s define a separate function for that.
def trigger_api(state): url = "https://mashvisor-api.p.rapidapi.com/trends/cities" querystring = {"page":"1","items":"10","state":state} headers = { 'x-rapidapi-host': RAPIDAPI_HOST, 'x-rapidapi-key': RAPIDAPI_KEY } response = requests.request("GET", url, headers=headers, params=querystring) if(200 == response.status_code): data = json.loads(response.text) if(data["status"] == "success"): return data["content"]["cities"] return None
The trigger_api( ) function accepts one argument, which is the postal code of the state. This argument is the mandatory parameter for the API, as we saw earlier. The querystring variable holds all the parameters passed to the API. For this script, we have chosen to show the bar chart for 10 top cities. Hence the value of “items” is set to 10.
This function returns a list of the cities identified by the “cities” key within the API response.
3. Define a function for plotting the chart
The data contained in the list of cities is filtered to extract the “city” and “total_listing”. These contain the name of the city and the numeric count of the total listings for that city.
A Python dictionary is used to store a list of cities and a list of counts of total listings. Here is how the data is arranged inside the dictionary under two keys “city” and “count” .
input_data[“city”] = [“Oakland”, “San Francisco”, “Los Angeles” ……
input_data[“count”] = [ 10624, 9307, 8024 ……
This dictionary is the input to the plotting function plot_graph( ).
def plot_graph(input_data): listing_counts = pd.Series(input_data["count"], index = input_data["city"]) df = pd.DataFrame({'Total Listings' : listing_counts}) df = df.sort_values(by='Total Listings') city_range=list(range(1,len(df.index)+1)) fig, ax = plt.subplots(figsize=(12,7)) plt.hlines(y=city_range, xmin=0, xmax=df['Total Listings'], color='#ec7b13', alpha=0.2, linewidth=5) plt.plot(df['Total Listings'], city_range, ">", markersize=5, color='#ec7b13', alpha=0.5) ax.set_xlabel('Total Listings') ax.set_ylabel('') ax.tick_params(axis='both', which='major', labelsize=10) plt.yticks(city_range, df.index) fig.text(0.23, 0.96, 'Airbnb Listings', fontsize=15, fontweight='black', color = '#333F4B') ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') plt.rcParams['axes.linewidth']=0.4 plt.rcParams['ytick.color']='#ec7b13' plt.tight_layout() plt.show()
A lot is happening inside this function. At first, the input_data is loaded in a Pandas data frame and sorted in descending order.
After this, the function calls a series of matplotlib library APIs to plot the bar graph. Most of the function calls to matplotlib library are for styling the visualization. However, the two most important calls are the hlines( ) and plot( ).
The hlines( ) function is used to draw a horizontal line. For each city, a horizontal line is drawn to the extent of the listing count of that city. Check out the function signature of hlines in the official matplotlib documentation.
The plot( ) function is used to plot a marker on the x, y axis. If you notice the bar chart displayed earlier, there is a pointed arrow-like symbol at the end of each horizontal bar. This is achieved using the ‘>’ character plotted with this function. More information can be obtained from the official matplotlib documentation.
The bars are styled with a shade of orange color.
4. Define the main logic
Now we are left with the main logic. Here is the code that goes inside the __main__ block.
if "__main__" == __name__: try: state_string = input("Enter state code: ") if(len(state_string) == 2): state_listing = trigger_api(state_string) input_data = dict() input_data["city"] = list() input_data["count"] = list() for listing in state_listing: input_data["city"].append(listing["city"]) input_data["count"].append(listing["total_listing"]) plot_graph(input_data) else: print("Invalid state code") except Exception as e: print ("Error") print (e)
At first, the script asks for user input to collect the postal code for the state. After that, the trigger_api( ) is called to retrieve the top 10 city trends for the state.
A for loop iterates over the list to extract the city name and the count of total listing and populates the input_data dictionary. The input_data gets passed as an argument to the plot_graph( ), which is responsible for plotting the bar graph.
Time for Some Airbnb Trend Analysis
Make sure you copy the code sequentially in the python file. Before saving, do not forget to replace the <YOUR_RAPIDAPI_KEY> with your RapidAPI subscription key.
You are now ready to test the script.
Open a terminal and fire the script with the Python 3 interpreter.
python airbnb_total_listing_chart.py
You must ensure that that Python 3 interpreter is in your system path, else the above command will not work. Alternatively, you can invoke it using the absolute path.
As per the logic defined earlier, the script prompts you for the state code. Assuming you enter a valid two-letter postal code of the state, the script fetches the trend data from API and displays the count of total listings for the top 10 cities in the state.
Wrapping Up
So that’s a wrap on this tutorial. We hope this demo has rekindled your mind to think in terms of visualizing data from APIs.
If you are a data visualization nerd, then you can mashup data from multiple endpoints of Mashvisor API to make more meaningful graphs for real-world analysis of real estate market trends. We will be back next week with another exciting API tutorial from the RapidAPI’s collection.
Leave a Reply