Travel Advisor

FREEMIUM
Verified
(Ким) Api Dojo | Оновлено 21 день назад | Transportation
Популярність

9.9 / 10

Затримки

2,758ms

Рівень обслуговування

100%

Health Check

N/A

Повернутися до всіх обговорень

Troubles with hotel request

Rapid account: Norskiy 88
norskiy88
14 дней назад

Hello! I’m getting an error when trying to request to hotel. What could be the problem? Here is my code

def request_to_city(city_name: str) -> List[Dict[str, Any]]:
url = "https://travel-advisor.p.rapidapi.com/locations/v2/auto-complete"
querystring = {“query”: city_name, “lang”: “ru_RU”}
headers = {
“x-rapidapi-host”: “travel-advisor.p.rapidapi.com”,
“x-rapidapi-key”: os.getenv(“RAPID_API_KEY”)
}

try:
    response = requests.get(url, params=querystring, headers=headers)
    response.raise_for_status()
    response_json = response.json()

    cities = []
    results = response_json.get("data", {}).get("Typeahead_autocomplete", {}).get("results", [])
    for result in results:
        city_info = result.get("detailsV2", {})
        city_name = city_info.get("names", {}).get("name")
        city_id = city_info.get("locationId")
        if city_name and city_id:
            cities.append({
                "city_name": city_name,
                "geoId": city_id
            })

    return cities

except requests.exceptions.RequestException as e:
    print("Error with request to API:", e)
    return []

def request_hotels(user_id: str, chat_id: str, sort_order: str, is_reverse: bool = False) -> Dict[str, Any]:
with bot.retrieve_data(user_id, chat_id) as hotels_data:
url = "https://travel-advisor.p.rapidapi.com/hotels/v2/list"
querystring = {“currency”: “RUB”, “lang”: “ru_RU”}

    headers = {
        "content-type": "application/json",
        "X-RapidAPI-Key": os.getenv("RAPID_API_KEY"),
        "X-RapidAPI-Host": "travel-advisor.p.rapidapi.com"
    }

    payload = {
        "geoId": hotels_data['city_id'],
        "checkIn": hotels_data['check_in'].strftime("%Y-%m-%d"),
        "checkOut": hotels_data['check_out'].strftime("%Y-%m-%d"),
        "sort": sort_order,
        "sortOrder": "asc",
        "filters": [
            {"id": "price", "value": [str(hotels_data['price_min']), str(hotels_data['price_max'])]}
        ],
        "rooms": [
            {"adults": 2, "childrenAges": [2]},
            {"adults": 2, "childrenAges": [3]}
        ],
        "boundingBox": {
            "northEastCorner": {"latitude": 12.248278039408776, "longitude": 109.1981618106365},
            "southWestCorner": {"latitude": 12.243407232845051, "longitude": 109.1921640560031}
        },
        "updateToken": ""
    }

    try:
        response = request_to_api("POST", url, json=payload, params=querystring, headers=headers)
        response.raise_for_status()
        response_json = response.json()

        if 'data' not in response_json or not response_json['data']:
            raise ValueError('Ошибка: Ответ не содержит ожидаемых данных')

        result = response_json['data'].get('AppPresentation_queryAppListV2')
        if not result:
            raise ValueError('Ошибка: Не удалось получить результаты поиска отелей')

        hotels = {}
        for item in result:
            if 'barItems' in item:
                for bar_item in item['barItems']:
                    if 'trackingKey' in bar_item and 'Map' in bar_item.get('buttonText', {}).get('string', ''):
                        hotels = bar_item.get('listItems', [])
                        break

        if is_reverse:
            hotels.reverse()

        data = {}
        for hotel in hotels:
            name = hotel.get('name')
            price = hotel.get('price')
            total_days = hotels_data['total_days'].days if hotels_data['total_days'].days != 0 else 1
            total_price = round(price * total_days) if isinstance(price, int) else None
            address, photos = request_photos(hotel_id=hotel.get('locationId'))

            rating_info = request_rating(hotel_id=hotel.get('locationId'))
            rating = rating_info.get('rating')

            data[name] = {
                'hotel_id': hotel.get('locationId'),
                'address': address,
                'distance': int(
                    hotel.get('destinationInfo', {}).get('distanceFromDestination', {}).get('value', 0)),
                'price': price,
                'total_price': total_price,
                'rating': rating,
                'link': f'https://www.hotels.com/h{hotel.get("locationId")}.Hotel-Information',
                'photos': photos
            }

        return data

    except Exception as e:
        print(f"Error when requesting: {e}")
        return {}
Rapid account: Apidojo
apidojo Commented 13 дней назад

Hello,

I am sorry that I cannot help you with coding. If you want to test the API to see whether or not it works, please use an HTTP client such as postman.com.

Regards.

Приєднуйтесь до обговорення — додайте повідомлення нижче:

Вхід / Реєстрація, щоб публікувати нові повідомлення