Python Integration Guide
Learn how to integrate BayutAPI into your Python application using the requests library. Covers authentication, searching properties, handling pagination, and error handling.
Prerequisites
- Python 3.7 or higher installed
- A RapidAPI account with a BayutAPI subscription (get your free API key)
- Basic familiarity with Python and REST APIs
Installation
Install the requests library if you donβt already have it:
pip install requests
Authentication
Every request to BayutAPI requires two headers. Your API key comes from your RapidAPI dashboard:
import requests
HEADERS = {
"x-rapidapi-key": "YOUR_API_KEY",
"x-rapidapi-host": "bayut14.p.rapidapi.com"
}
BASE_URL = "https://bayut14.p.rapidapi.com"
Replace YOUR_API_KEY with the key from your RapidAPI dashboard.
Basic Example: Search Properties
Search for properties for sale in a specific location:
import requests
HEADERS = {
"x-rapidapi-key": "YOUR_API_KEY",
"x-rapidapi-host": "bayut14.p.rapidapi.com"
}
# Search for 2-bedroom apartments for sale
response = requests.get(
"https://bayut14.p.rapidapi.com/search-property",
headers=HEADERS,
params={
"purpose": "for-sale",
"location_ids": "5002", # Dubai Marina
"bedrooms_min": "2",
"bedrooms_max": "2",
"page": "1"
}
)
data = response.json()
print(f"Total results: {data['data']['total']}")
print(f"Page {data['data']['page']} of {data['data']['totalPages']}")
print()
for prop in data["data"]["properties"]:
print(f"Title: {prop['title']['en']}")
print(f"Price: AED {prop['price']:,}")
print(f"Area: {prop.get('area', 'N/A')} sqft")
print(f"Location: {prop.get('location', 'N/A')}")
print("---")
Location Autocomplete
Before searching properties, use autocomplete to find the correct location ID:
def search_location(query):
"""Search for locations and return matches with IDs."""
response = requests.get(
"https://bayut14.p.rapidapi.com/autocomplete",
headers=HEADERS,
params={"query": query, "langs": "en"}
)
response.raise_for_status()
results = response.json()
locations = []
for hit in results.get("data", {}).get("locations", []):
locations.append({
"name": hit.get("name"),
"id": hit.get("externalID"),
"type": hit.get("type")
})
return locations
# Find location IDs
locations = search_location("jumeirah")
for loc in locations:
print(f"{loc['name']} (ID: {loc['id']}, Type: {loc['type']})")
Advanced Example: Pagination
Fetch multiple pages of results to build a complete dataset:
def fetch_all_listings(location_id, purpose="for-sale", max_pages=10):
"""Fetch listings across multiple pages."""
all_listings = []
page = 1
while page <= max_pages:
response = requests.get(
"https://bayut14.p.rapidapi.com/search-property",
headers=HEADERS,
params={
"purpose": purpose,
"location_ids": location_id,
"page": str(page)
}
)
response.raise_for_status()
data = response.json()
hits = data["data"]["properties"]
if not hits:
break
all_listings.extend(hits)
print(f"Page {page}/{data['data']['totalPages']}: fetched {len(hits)} listings")
if page >= data["data"]["totalPages"]:
break
page += 1
return all_listings
listings = fetch_all_listings("5002", max_pages=3)
print(f"\nTotal fetched: {len(listings)} listings")
Error Handling
Always handle API errors gracefully in production code:
def safe_api_call(url, params):
"""Make an API call with proper error handling."""
try:
response = requests.get(url, headers=HEADERS, params=params, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
print("Request timed out. Try again later.")
return None
except requests.exceptions.HTTPError as e:
if response.status_code == 429:
print("Rate limit exceeded. Wait before retrying.")
elif response.status_code == 400:
print(f"Bad request: {response.json().get('message', 'Unknown error')}")
else:
print(f"HTTP error {response.status_code}: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
# Usage
result = safe_api_call(
"https://bayut14.p.rapidapi.com/search-property",
{"purpose": "for-sale", "page": "1"}
)
if result:
print(f"Found {result['data']['total']} properties")
Next Steps
- Explore the full API documentation for all available endpoints and parameters
- Check out the Investment Analysis use case for data analysis examples
- Try the AI & Machine Learning guide for building ML models with property data
- Visit the RapidAPI dashboard to test endpoints interactively