Skip to content

Instantly share code, notes, and snippets.

@angelabauer
Created October 21, 2020 10:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save angelabauer/a36dc61abd1e722a91b5d4da67ec56dc to your computer and use it in GitHub Desktop.
Save angelabauer/a36dc61abd1e722a91b5d4da67ec56dc to your computer and use it in GitHub Desktop.
class FlightData:
def __init__(self, price, origin_city, origin_airport, destination_city, destination_airport, out_date, return_date):
self.price = price
self.origin_city = origin_city
self.origin_airport = origin_airport
self.destination_city = destination_city
self.destination_airport = destination_airport
self.out_date = out_date
self.return_date = return_date
import requests
from flight_data import FlightData
TEQUILA_ENDPOINT = "https://tequila-api.kiwi.com"
TEQUILA_API_KEY = YOUR FLIGHT SEARCH API KEY
class FlightSearch:
def get_destination_code(self, city_name):
location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
headers = {"apikey": TEQUILA_API_KEY}
query = {"term": city_name, "location_types": "city"}
response = requests.get(url=location_endpoint, headers=headers, params=query)
results = response.json()["locations"]
code = results[0]["code"]
return code
def check_flights(self, origin_city_code, destination_city_code, from_time, to_time):
headers = {"apikey": TEQUILA_API_KEY}
query = {
"fly_from": origin_city_code,
"fly_to": destination_city_code,
"date_from": from_time.strftime("%d/%m/%Y"),
"date_to": to_time.strftime("%d/%m/%Y"),
"nights_in_dst_from": 7,
"nights_in_dst_to": 28,
"flight_type": "round",
"one_for_city": 1,
"max_stopovers": 0,
"curr": "GBP"
}
response = requests.get(
url=f"{TEQUILA_ENDPOINT}/v2/search",
headers=headers,
params=query,
)
data = response.json()["data"][0]
# pprint(data)
flight_data = FlightData(
price=data["price"],
origin_city=data["route"][0]["cityFrom"],
origin_airport=data["route"][0]["flyFrom"],
destination_city=data["route"][0]["cityTo"],
destination_airport=data["route"][0]["flyTo"],
out_date=data["route"][0]["local_departure"].split("T")[0],
return_date=data["route"][1]["local_departure"].split("T")[0]
)
print(f"{flight_data.destination_city}: £{flight_data.price}")
return flight_data
from datetime import datetime, timedelta
from data_manager import DataManager
from flight_search import FlightSearch
data_manager = DataManager()
sheet_data = data_manager.get_destination_data()
flight_search = FlightSearch()
ORIGIN_CITY_IATA = "LON"
if sheet_data[0]["iataCode"] == "":
for row in sheet_data:
row["iataCode"] = flight_search.get_destination_code(row["city"])
data_manager.destination_data = sheet_data
data_manager.update_destination_codes()
tomorrow = datetime.now() + timedelta(days=1)
six_month_from_today = datetime.now() + timedelta(days=(6 * 30))
for destination in sheet_data:
flight = flight_search.check_flights(
ORIGIN_CITY_IATA,
destination["iataCode"],
from_time=tomorrow,
to_time=six_month_from_today
)
@RunesReader
Copy link

RunesReader commented Jan 24, 2021

flight_search.py file:
Sometimes we can get empty array when we are trying to parse server response response.json()["data"]
So, it would be great to check the array before we access it by index

raw_data = response.json()["data"]
        if raw_data:
            data = raw_data[0]
            flight_data = FlightData(
                price=data["price"],
                origin_city=data["route"][0]["cityFrom"],
                origin_airport=data["route"][0]["flyFrom"],
                destination_city=data["route"][0]["cityTo"],
                destination_airport=data["route"][0]["flyTo"],
                out_date=data["route"][0]["local_departure"].split("T")[0],
                return_date=data["route"][1]["local_departure"].split("T")[0]
            )
            print(f"{flight_data.destination_city}: ${flight_data.price}")
            return flight_data
        else:
            return None

@Anshu-webDev
Copy link

{'error_code': 403, 'message': "You don't have permission to access this resource"}
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\pythonProject\flight-deals-start\main.py", line 25, in
flight = flight_search.check_flights(
File "C:\Users\Admin\PycharmProjects\pythonProject\flight-deals-start\flight_search.py", line 54, in check_flights
data = result["data"][0]
KeyError: 'data'

@Anshu-webDev
Copy link

it giving me an error

@RakeshPotnuru
Copy link

it giving me an error

{'error_code': 403, 'message': "You don't have permission to access this resource"}
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\pythonProject\flight-deals-start\main.py", line 25, in
flight = flight_search.check_flights(
File "C:\Users\Admin\PycharmProjects\pythonProject\flight-deals-start\flight_search.py", line 54, in check_flights
data = result["data"][0]
KeyError: 'data'

Create a new solution with Meta Search API Integration and in search type choose One way and Return

@riquew
Copy link

riquew commented Feb 4, 2022

Monthly quota has been reached. Please upgrade to continue making requests.
:(

@Audran-wol
Copy link

Clean Code it works great

@RhythmBear
Copy link

Its giving a 403 response code

@schmackygit
Copy link

@angelabauer are you able to help with KeyError: 'data' issues?

@schmackygit
Copy link

/usr/bin/python3.9 /home/schmacky/Projects/flight checker/main.py
Traceback (most recent call last):
File "/home/schmacky/Projects/flight checker/main.py", line 34, in
flight = flight_search.check_flights(
File "/home/schmacky/Projects/flight checker/flight_search.py", line 48, in check_flights
data = response.json()["data"][0]
KeyError: 'data'

Process finished with exit code 1

@mpreams
Copy link

mpreams commented May 20, 2023

the response.json() I'm getting from KIWI is either exactly what I'm expecting or it's
"{'status': 'Bad Request', 'error': 'unknown partner provided - if you would like to cooperate with Kiwi.com, please register at tequila.kiwi.com'}".
I'm having it repeat the request for each city with a for loop so nothing changes per iteration but the destination city (I've tried to only supply required parameters), yet it randomly works and randomly doesn't with the exact same code, run multiple times, it seems entirely random if it works or not. Any clue why? It has given a proper response with an empty list for "data" as well, it just randomly (although its most of the time) responds with said error.

@avadhut-the-merciful
Copy link

Since Sheety allows 200 requests per month for free accounts delete a few entries in the Google sheet to save the requests. Currently, there are 11 entries so every time we run the code it takes 11 requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment