We are back with the Mashvisor API again. This time it’s going to be a Vue.js widget for searching Airbnb listings.
Mashvisor API has an extensive set of API endpoints to assist you with real estate data. For this blog post, we are going to take a closer look at Airbnb’s short term rental listings via the Mashvisor API. Subsequently, we will show you how to build a Vue.js based demo app to search Airbnb listings using the Mashvisor API.
Getting Started with Airbnb Listing using Mashvisor API
If you are new to Mashvisor API then just a word of caution. You might get swamped with a lot of options for enquiring property-related data, such as prices, listings, historical performances, trends. It’s a gold mine of data, served by nearly 40 API endpoints.
Let’s take a peek into the API console and explore the options for Airbnb short term rentals. Here are the steps to get started with 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 alternatively 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. Test the API Endpoint for Retrieving Airbnb Listings
Our focus for this blog post is on the short term rentals in Airbnb. You can find the API endpoint for this, on the left panel on the API console.
Select the “GET Get Listings” endpoint. You will be presented with a few parameters to invoke the API.
The default parameter values indicate a search query to retrieve listings for San Francisco, California. It also specifies a zip code, however, a zip code specific search is too narrow and is bound to return empty results. Therefore, it is best to search based on city and state.
Clear off the ‘zip_code’ parameter value and hit the “Test Endpoint” button. You should see an API response containing four Airbnb listings.
You can increase the number of listings returned in the API response by setting the values for ‘page’ and ‘items’ parameters.
A look at the right-side panel of the API console reveals the code snippet used to invoke this API. You can choose from among many languages to programmatically invoke the API. Here is how the code snippet looks like for the Javascript fetch( ) function.
Expanding one of the listings from API response reveals more information about the property.
This gives you some essential data about the property, such as pricing, type of property, location, number of beds, as well as a picture of the property.
With this information, you can build an Airbnb search widget that can be embedded into an app.
How To Build Airbnb Search Widget using Vue.js
Vue.js is one of the upcoming Javascript UI frameworks for building web applications. It’s loosely coupled component-based approach to define UI elements is well suited for building web applications. Further, it is easier to adopt for web developers compared to the more full-featured and opinionated frameworks such as Angular and React.
If you are a web developer and curious about Vue.js then check out the official Vue.js docs to know more.
For this demo, we build a single page app based on a Vue.js component. This component houses the search panel and the search result display panel. Here is how it looks with the search results displayed.
The search panel is pre-configured to select three cities, San Francisco, Buffalo, and Houston. Upon selecting the city and clicking on the red “Search Listings” button, the app fetches the first 6 results from the “GET Get Listings” endpoint and displays the results along with the image of the property.
Are you excited to see how to use the Mashvisor API with this Vue.js app? Then let’s start coding now.
Create a project folder for this app, and fire up your favorite code editor. You are all set.
Step 1: Create the HTML skeleton file
Create a new .html file called index.html. This will be the main web page of the app.
<!DOCTYPE html> <html lang="en"> <head> <!-- Responsive + Encoding Meta Tag --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheet --> <link href = "styles.css" rel = "stylesheet"> <!-- Title --> <title>Airbnb - Mashvisor API</title> </head> <body> </body> <!-- Vue and Custom JavaScript --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <script src = "scripts.js"></script> </html>
Take a look at the application-specific CSS and Javascript files that are imported here.
styles.css: This is the custom CSS file to style the search panel and the results
scripts.js: This is the custom Javascript file where you define the Vue components.
Apart from this, the HTML file also pulls in the latest Vue package from its official CDN. The Vue.js version is 2.6.11.
Now, let’s populate the <body> element with the UI components for this app.
Step 2: Add the HTML elements for rendering the DOM.
Add the following code within the <body> tag.
<!-- Main App --> <div id="airbnb"> <h1 id = "main-heading">Airbnb Short Term Rentals using Mashvisor API</h1> <div id = "search-container"> <select id = "city-state" v-model = "city"> <option value = "">--Choose City, State --</option> <option value = "SFCA">San Francisco, CA</option> <option value = "BNY">Buffalo, NY</option> <option value = "HTX">Houston, TX</option> </select> <button type = "button" id = "search-btn" @click = "clickSearch">Search Listings</button> <h4 id = "search-meta" v-if = "searchClicked && results.length != 0">Top 6 Results</h4> </div> <div id = "result-container" v-if = "results.length != 0"> <div class = "result" v-for = "(result,index) in results" :key = "index"> <img :src = "result.image" class = "prop-img"> <h4 class = "rating"> {{result.start_rating}}/5 ({{result.reviews_count}} reviews)</h4> <h3 class = "property-name">{{result.name}}</h3> <h5 class = "property-address">{{result.address}}</h5> <p class = "capacity">Capacity: {{result.capacity_of_people}} people</p> <p class = "prices">Night Price : ${{result.night_price}} <br> Weekly Price: ${{result.weekly_price}} <br> Monthly Price: ${{result.monthly_price}}</p> </div> </div> </div>
Inside the top-level <div> element, there are two containers identified by the ids, ‘search-container’ and ‘result-container’. These represent the search and the results panel respectively.
Apart from the usual HTML attributes, you can also notice some attributes which are Vue specific directives. The ‘v-if’ and the ‘v-for’ directives are used to program in the DOM rendering. This is used for displaying and looping through the results after the API response is received.
Additionally, there is a ‘v-model’ directive, which is used to bind the data variable named city to the <option> value of the <select> tag. This variable is declared inside the Vue component instance that you will code next.
Step 3: Define the Vue Component
Now it’s time to define the instance for the Vue component that renders the HTML file. You can start with a basic template of a Vue.js component as follows.
Create a new file named scritps.js in the same path as the HTML file and add the following code for the Vue component.
const app = new Vue({ el: '#airbnb', data: { results: [], searchClicked: false, city: '', apiKey: '<YOUR_RAPIDAPI_KEY>' }, methods: { clickSearch() { }, getData(city) { } } })
The Vue component definition consists of an options object that defines three keys.
el: This is the HTML element’s id selector which is bound to the Vue component. In this case, the element is <div id=”airbnb”> which is the top-level element inside <body> tag.
data: This contains a set of linking variables that control the rendering of the DOM based on the state and user data for this component. The searchClicked maintains the state of search initiation. results and city are bound to the HTML DOM elements and are used for displaying the results.
The apiKey contains the RapidAPI key which is used for invoking the API call. Make sure to replace the placeholder ‘<YOUR_RAPIDAPI_KEY>’ with your actual subscription key.
Step 4: Define the Logic for Search and Display of Airbnb Listings
There are two methods in the Vue component, clickSearch( ) and getData( ).
The clickSearch( ) is used to initiate a search for Airbnb listings as per the code below.
clickSearch() { this.searchClicked = true this.getData(this.city) }
It sets the state of searchClicked to true and invokes the getData( ) which is defined as follows.
getData(city) { let uri = '' this.results = [] if(city == "SFCA") { uri = 'https://mashvisor-api.p.rapidapi.com/airbnb-property/active-listings?page=1&city=San%20Francisco&items=6&state=CA' } else if(city == "BNY") { uri = 'https://mashvisor-api.p.rapidapi.com/airbnb-property/active-listings?page=1&city=Buffalo&items=6&state=NY' } else if(city == "HTX") { uri = 'https://mashvisor-api.p.rapidapi.com/airbnb-property/active-listings?page=1&city=Houston&items=6&state=TX' } else { alert("Please choose an option") } let res = [] if(uri != '') { fetch(uri, { "method": "GET", "headers": { "x-rapidapi-host": "mashvisor-api.p.rapidapi.com", "x-rapidapi-key": this.apiKey } }) .then(response => { if(response.ok) { response.json() .then(response1 => { this.results = response1.content.properties if(this.results.length == 0) { alert('No listings found.') } }) } }) .catch(err => { alert("The API is facing issues. Please try again later.n" + err) }) } }
The logic is pretty simple. The URL for the Mashvisor API is created based on the selected city in the dropdown. This is in accordance with the code snippet for “GET Get Listings” endpoint that you have seen earlier while testing the API.
Based on the URL, the Javascript fetch( ) function is called to trigger the API. The API response is assigned to the results key of data defined in the options object for the Vue component. In the HTML file, the Vue directive ‘v-for’ is used to loop through the results and render the listings.
Step 5: Define the Style for Displaying the Results
The last thing remaining for the app to be completed is the styling. In the index.html file, there is one CSS file that is imported. It defines all the CSS classes and settings for styling the UI. You can create a new file named styles.css and copy the below code into it.
@import url('https://fonts.googleapis.com/css?family=Sen&display=swap'); @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap'); #main-heading { text-align: center; font-family: 'Sen', sans-serif; padding: 20px; border-bottom: 2px solid #000; width: 50%; margin: auto; } #search-container { width: 80%; margin: 30px auto; text-align: center; } #city-state { padding: 12px; margin: auto; border: 1px solid #f4f4f4; text-align: center !important; border: 1px solid #ccc; } #search-btn { border: none; background-color: #FF5A5F; color: white; padding: 13px; border-radius: 5px; font-weight: 500; letter-spacing: 1px; font-family: 'Roboto', sans-serif; } #search-meta { font-weight: normal; color: #888888; font-family: 'Roboto', sans-serif; } #result-container { width: 60%; margin: 30px auto; text-align: center; } .result { border-radius: 10px; box-shadow: 3px 3px 15px #ccc; width: 40%; margin: 20px auto; text-align: center; display: inline-block; } .prop-img { padding: 10px; border-radius: 10px; } .result h1,h2,h3,h4,h5,h6 { padding: 0; margin: 0; } .rating { color: rgba(0,0,0,0.7); font-family: 'Roboto', sans-serif; } .property-name { font-size: 18px; font-family: 'Sen', sans-serif; } .property-address { color: rgba(0,0,0,0.7); font-family: 'Roboto', sans-serif; } .capacity, .prices { margin: 0; padding: 10px; font-family: 'Roboto', sans-serif; } @media screen and (max-width: 768px) { #main-heading { font-size: 14px; width: 80%; } .result { display: block; width: 90%; } .property-name { font-size: 16px; } #result-container { width: 100%; } .prop-img { width: 90%; } }
With this, your app is now complete.
In the end, you will have three files, index.html, scripts.js, and styles.css, in the same directory path.
Let’s Go Hunting For Airbnb Places
Yeah, you are almost there.
Fire up a web browser and open the index.html file. Now you can search for the short term rental listings from either San Francisco, Buffalo or Houston.
As you have witnessed in this app, Vue.js makes it really easy to build modular UI components like this. Although this is a standalone web app, it can be inserted into an existing web application as well. Additionally, Vue.js also offers a full-featured tooling option with Vue CLI to build highly interactive web apps from the grounds up.
We will be back soon with more engaging demos of RapidAPI hosted APIs with Vue.js.
Leave a Reply