Hey there, fellow developer! Ready to dive into the world of apartment hunting with code? We're about to embark on a journey to integrate the Apartments.com API into your Python project. This powerful API will let you tap into a vast database of rental listings, making your apartment search app dreams a reality.
Before we jump in, make sure you've got:
Let's kick things off by setting up our API client:
import requests API_KEY = 'your_api_key_here' BASE_URL = 'https://api.apartments.com/v1' headers = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' }
Now, let's make our first API call:
def get_apartments(endpoint, params=None): response = requests.get(f'{BASE_URL}/{endpoint}', headers=headers, params=params) response.raise_for_status() return response.json() # Example: Get all apartments in New York City nyc_apartments = get_apartments('apartments', params={'city': 'New York', 'state': 'NY'})
Time to build some more complex searches:
def search_apartments(city, state, min_price=None, max_price=None): params = { 'city': city, 'state': state, 'minPrice': min_price, 'maxPrice': max_price } return get_apartments('apartments', params=params) # Find apartments in San Francisco between $2000 and $3000 sf_apartments = search_apartments('San Francisco', 'CA', 2000, 3000)
Let's dig deeper into a specific property:
def get_property_details(property_id): return get_apartments(f'properties/{property_id}') # Get details for a specific property property_details = get_property_details('abc123')
Dealing with lots of results? No problem:
def get_all_results(endpoint, params=None): all_results = [] page = 1 while True: params['page'] = page response = get_apartments(endpoint, params) all_results.extend(response['results']) if not response['hasNextPage']: break page += 1 return all_results
Let's add some robustness to our requests:
import time from requests.exceptions import RequestException def api_request_with_retry(endpoint, params=None, max_retries=3): for attempt in range(max_retries): try: return get_apartments(endpoint, params) except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff
Keep things speedy with some basic caching:
import json from datetime import datetime, timedelta def cache_results(key, data, expiry_hours=24): with open(f'{key}.json', 'w') as f: json.dump({ 'data': data, 'expiry': (datetime.now() + timedelta(hours=expiry_hours)).isoformat() }, f) def get_cached_results(key): try: with open(f'{key}.json', 'r') as f: cached = json.load(f) if datetime.fromisoformat(cached['expiry']) > datetime.now(): return cached['data'] except (FileNotFoundError, json.JSONDecodeError, KeyError): pass return None
Let's add some cool filtering and geolocation features:
def search_apartments_near_location(latitude, longitude, radius_miles): params = { 'lat': latitude, 'lon': longitude, 'radius': radius_miles } return get_apartments('apartments/nearby', params=params) # Find apartments within 5 miles of the Empire State Building nearby_apartments = search_apartments_near_location(40.7484, -73.9857, 5)
Here's a complete script that brings it all together:
import requests import json from datetime import datetime, timedelta import time # ... (include all the functions we've defined above) def main(): # Search for apartments in Chicago chicago_apartments = search_apartments('Chicago', 'IL', 1500, 2500) # Cache the results cache_results('chicago_apartments', chicago_apartments) # Get detailed info for the first apartment if chicago_apartments['results']: first_apartment = chicago_apartments['results'][0] details = get_property_details(first_apartment['id']) print(json.dumps(details, indent=2)) # Search for apartments near a specific location nearby = search_apartments_near_location(41.8781, -87.6298, 2) # Near Chicago's city center print(f"Found {len(nearby['results'])} apartments nearby") if __name__ == '__main__': main()
And there you have it! You've just built a robust Apartments.com API integration in Python. You can now search for apartments, get detailed property information, handle pagination, and even perform location-based searches.
Remember, this is just the beginning. You could expand this further by adding a user interface, integrating with mapping services, or even building a recommendation system. The possibilities are endless!
Happy coding, and may your apartment hunting be ever in your favor!