fast-flights


Namefast-flights JSON
Version 0.3 PyPI version JSON
download
home_pageNone
SummaryThe fast, robust, strongly-typed Google Flights scraper (API) implemented in Python.
upload_time2024-05-20 08:33:47
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseNone
keywords flights google google-flights scraper protobuf travel trip passengers airport
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">

# flights (fast-flights)

The fast, robust, strongly-typed Google Flights scraper (API) implemented in Python. Based on Base64-encoded Protobuf string.

```haskell
$ pip install fast-flights
```

</div>

## Usage

To use `fast-flights`, you'll first create a filter (inherited from `?tfs=`) to perform a request.
Then, add `flight_data`, `trip`, `seat` and `passengers` info to use the API directly.

Honorable mention: I like birds. Yes, I like birds.

```python
from fast_flights import FlightData, Passengers, create_filter, get_flights

# Create a new filter
filter = create_filter(
    flight_data=[
        # Include more if it's not a one-way trip
        FlightData(
            date="2024-07-02",  # Date of departure
            from_airport="TPE", 
            to_airport="MYJ"
        ),
        # ... include more for round trips and multi-city trips
    ],
    trip="one-way",  # Trip (round-trip, one-way, multi-city)
    seat="economy",  # Seat (economy, premium economy, business or first)
    passengers=Passengers(
        adults=2,
        children=1,
        infants_in_seat=0,
        infants_on_lap=0
    ),
)

# Get flights with a filter
result = get_flights(filter)

# The price is currently... low/typical/high
print("The price is currently", result.current_price)

# Display the first flight
print(result.flights[0])
```

Additionally, you can use the `Airport` enum to search for airports in code (as you type)! (See `_generated_enum.py` in source)

```python
Airport.TAIPEI
              |---------------------------------|
              | TAIPEI_SONGSHAN_AIRPORT         |
              | TAPACHULA_INTERNATIONAL_AIRPORT |
              | TAMPA_INTERNATIONAL_AIRPORT     |
              | ... 5 more                      |
              |---------------------------------|
```

## How it's made

The other day, I was making a chat-interface-based trip recommendation app and wanted to add a feature that can search for flights available for booking. My personal choice is definitely [Google Flights](https://flights.google.com) since Google always has the best and most organized data on the web. Therefore, I searched for APIs on Google.

> 🔎 **Search** <br />
> google flights api

The results? Bad. It seems like they discontinued this service and it now lives in the Graveyard of Google.

> <sup><a href="https://duffel.com/blog/google-flights-api" target="_blank">🧏‍♂️ <b>duffel.com</b></a></sup><br />
> <sup><i>Google Flights API: How did it work & what happened to it?</i></b>
>
> The Google Flights API offered developers access to aggregated airline data, including flight times, availability, and prices. Over a decade ago, Google announced the acquisition of ITA Software Inc. which it used to develop its API. **However, in 2018, Google ended access to the public-facing API and now only offers access through the QPX enterprise product**.

That's awful! I've also looked for free alternatives but their rate limits and pricing are just 😬 (not a good fit/deal for everyone).

<br />

However, Google Flights has their UI – [flights.google.com](https://flights.google.com). So, maybe I could just use Developer Tools to log the requests made and just replicate all of that? Undoubtedly not! Their requests are just full of numbers and unreadable text, so that's not the solution.

Perhaps, we could scrape it? I mean, Google allowed many companies like [Serpapi](https://google.com/search?q=serpapi) to scrape their web just pretending like nothing happened... So let's scrape our own.

> 🔎 **Search** <br />
> google flights ~~api~~ scraper pypi

Excluding the ones that are not active, I came across [hugoglvs/google-flights-scraper](https://pypi.org/project/google-flights-scraper) on Pypi. I thought to myself: "aint no way this is the solution!"

I checked hugoglvs's code on [GitHub](https://github.com/hugoglvs/google-flights-scraper), and I immediately detected "playwright," my worst enemy. One word can describe it well: slow. Two words? Extremely slow. What's more, it doesn't even run on the **🗻 Edge** because of configuration errors, missing libraries... etc. I could just reverse [try.playwright.tech](https://try.playwright.tech) and use a better environment, but that's just too risky if they added Cloudflare as an additional security barrier 😳.

Life tells me to never give up. Let's just take a look at their URL params...

```markdown
https://www.google.com/travel/flights/search?tfs=CBwQAhoeEgoyMDI0LTA1LTI4agcIARIDVFBFcgcIARIDTVlKGh4SCjIwMjQtMDUtMzBqBwgBEgNNWUpyBwgBEgNUUEVAAUgBcAGCAQsI____________AZgBAQ&hl=en
```

| Param | Content | My past understanding |
|-------|---------|-----------------------|
| hl    | en      | Sets the language.    |
| tfs   | CBwQAhoeEgoyMDI0LTA1LTI4agcIARID… | What is this???? 🤮🤮 |

I removed the `?tfs=` parameter and found out that this is the control of our request! And it looks so base64-y.

If we decode it to raw text, we can still see the dates, but we're not quite there — there's too much unwanted Unicode text.

Or maybe it's some kind of a **data-storing method** Google uses? What if it's something like JSON? Let's look it up.

> 🔎 **Search** <br />
> google's json alternative

> 🐣 **Result**<br />
> Solution: The Power of **Protocol Buffers**
> 
> LinkedIn turned to Protocol Buffers, often referred to as **protobuf**, a binary serialization format developed by Google. The key advantage of Protocol Buffers is its efficiency, compactness, and speed, making it significantly faster than JSON for serialization and deserialization.

Gotcha, Protobuf! Let's feed it to an online decoder and see how it does:

> 🔎 **Search** <br />
> protobuf decoder

> 🐣 **Result**<br />
> [protobuf-decoder.netlify.app](https://protobuf-decoder.netlify.app)

I then pasted the Base64-encoded string to the decoder and no way! It DID return valid data!

![annotated, Protobuf Decoder screenshot](https://github.com/AWeirdDev/flights/assets/90096971/77dfb097-f961-4494-be88-3640763dbc8c)

I immediately recognized the values — that's my data, that's my query!

So, I wrote some simple Protobuf code to decode the data.

```protobuf
syntax = "proto3"

message Airport {
    string name = 2;
}

message FlightInfo {
    string date = 2;
    Airport dep_airport = 13;
    Airport arr_airport = 14;
}

message GoogleSucks {
    repeated FlightInfo = 3;
}
```

It works! Now, I won't consider myself an "experienced Protobuf developer" but rather a complete beginner.

I have no idea what I wrote but... it worked! And here it is, `fast-flights`.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fast-flights",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "flights, google, google-flights, scraper, protobuf, travel, trip, passengers, airport",
    "author": null,
    "author_email": "AWeirdDev <aweirdscratcher@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/b9/e1/5daa9f7608af9517baa442289fc04845db68dd16da5e086d554bc5b710e9/fast_flights-0.3.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n\n# flights (fast-flights)\n\nThe fast, robust, strongly-typed Google Flights scraper (API) implemented in Python. Based on Base64-encoded Protobuf string.\n\n```haskell\n$ pip install fast-flights\n```\n\n</div>\n\n## Usage\n\nTo use `fast-flights`, you'll first create a filter (inherited from `?tfs=`) to perform a request.\nThen, add `flight_data`, `trip`, `seat` and `passengers` info to use the API directly.\n\nHonorable mention: I like birds. Yes, I like birds.\n\n```python\nfrom fast_flights import FlightData, Passengers, create_filter, get_flights\n\n# Create a new filter\nfilter = create_filter(\n    flight_data=[\n        # Include more if it's not a one-way trip\n        FlightData(\n            date=\"2024-07-02\",  # Date of departure\n            from_airport=\"TPE\", \n            to_airport=\"MYJ\"\n        ),\n        # ... include more for round trips and multi-city trips\n    ],\n    trip=\"one-way\",  # Trip (round-trip, one-way, multi-city)\n    seat=\"economy\",  # Seat (economy, premium economy, business or first)\n    passengers=Passengers(\n        adults=2,\n        children=1,\n        infants_in_seat=0,\n        infants_on_lap=0\n    ),\n)\n\n# Get flights with a filter\nresult = get_flights(filter)\n\n# The price is currently... low/typical/high\nprint(\"The price is currently\", result.current_price)\n\n# Display the first flight\nprint(result.flights[0])\n```\n\nAdditionally, you can use the `Airport` enum to search for airports in code (as you type)! (See `_generated_enum.py` in source)\n\n```python\nAirport.TAIPEI\n              |---------------------------------|\n              | TAIPEI_SONGSHAN_AIRPORT         |\n              | TAPACHULA_INTERNATIONAL_AIRPORT |\n              | TAMPA_INTERNATIONAL_AIRPORT     |\n              | ... 5 more                      |\n              |---------------------------------|\n```\n\n## How it's made\n\nThe other day, I was making a chat-interface-based trip recommendation app and wanted to add a feature that can search for flights available for booking. My personal choice is definitely [Google Flights](https://flights.google.com) since Google always has the best and most organized data on the web. Therefore, I searched for APIs on Google.\n\n> \ud83d\udd0e **Search** <br />\n> google flights api\n\nThe results? Bad. It seems like they discontinued this service and it now lives in the Graveyard of Google.\n\n> <sup><a href=\"https://duffel.com/blog/google-flights-api\" target=\"_blank\">\ud83e\uddcf\u200d\u2642\ufe0f <b>duffel.com</b></a></sup><br />\n> <sup><i>Google Flights API: How did it work & what happened to it?</i></b>\n>\n> The Google Flights API offered developers access to aggregated airline data, including flight times, availability, and prices. Over a decade ago, Google announced the acquisition of ITA Software Inc. which it used to develop its API. **However, in 2018, Google ended access to the public-facing API and now only offers access through the QPX enterprise product**.\n\nThat's awful! I've also looked for free alternatives but their rate limits and pricing are just \ud83d\ude2c (not a good fit/deal for everyone).\n\n<br />\n\nHowever, Google Flights has their UI \u2013 [flights.google.com](https://flights.google.com). So, maybe I could just use Developer Tools to log the requests made and just replicate all of that? Undoubtedly not! Their requests are just full of numbers and unreadable text, so that's not the solution.\n\nPerhaps, we could scrape it? I mean, Google allowed many companies like [Serpapi](https://google.com/search?q=serpapi) to scrape their web just pretending like nothing happened... So let's scrape our own.\n\n> \ud83d\udd0e **Search** <br />\n> google flights ~~api~~ scraper pypi\n\nExcluding the ones that are not active, I came across [hugoglvs/google-flights-scraper](https://pypi.org/project/google-flights-scraper) on Pypi. I thought to myself: \"aint no way this is the solution!\"\n\nI checked hugoglvs's code on [GitHub](https://github.com/hugoglvs/google-flights-scraper), and I immediately detected \"playwright,\" my worst enemy. One word can describe it well: slow. Two words? Extremely slow. What's more, it doesn't even run on the **\ud83d\uddfb Edge** because of configuration errors, missing libraries... etc. I could just reverse [try.playwright.tech](https://try.playwright.tech) and use a better environment, but that's just too risky if they added Cloudflare as an additional security barrier \ud83d\ude33.\n\nLife tells me to never give up. Let's just take a look at their URL params...\n\n```markdown\nhttps://www.google.com/travel/flights/search?tfs=CBwQAhoeEgoyMDI0LTA1LTI4agcIARIDVFBFcgcIARIDTVlKGh4SCjIwMjQtMDUtMzBqBwgBEgNNWUpyBwgBEgNUUEVAAUgBcAGCAQsI____________AZgBAQ&hl=en\n```\n\n| Param | Content | My past understanding |\n|-------|---------|-----------------------|\n| hl    | en      | Sets the language.    |\n| tfs   | CBwQAhoeEgoyMDI0LTA1LTI4agcIARID\u2026 | What is this???? \ud83e\udd2e\ud83e\udd2e |\n\nI removed the `?tfs=` parameter and found out that this is the control of our request! And it looks so base64-y.\n\nIf we decode it to raw text, we can still see the dates, but we're not quite there \u2014 there's too much unwanted Unicode text.\n\nOr maybe it's some kind of a **data-storing method** Google uses? What if it's something like JSON? Let's look it up.\n\n> \ud83d\udd0e **Search** <br />\n> google's json alternative\n\n> \ud83d\udc23 **Result**<br />\n> Solution: The Power of **Protocol Buffers**\n> \n> LinkedIn turned to Protocol Buffers, often referred to as **protobuf**, a binary serialization format developed by Google. The key advantage of Protocol Buffers is its efficiency, compactness, and speed, making it significantly faster than JSON for serialization and deserialization.\n\nGotcha, Protobuf! Let's feed it to an online decoder and see how it does:\n\n> \ud83d\udd0e **Search** <br />\n> protobuf decoder\n\n> \ud83d\udc23 **Result**<br />\n> [protobuf-decoder.netlify.app](https://protobuf-decoder.netlify.app)\n\nI then pasted the Base64-encoded string to the decoder and no way! It DID return valid data!\n\n![annotated, Protobuf Decoder screenshot](https://github.com/AWeirdDev/flights/assets/90096971/77dfb097-f961-4494-be88-3640763dbc8c)\n\nI immediately recognized the values \u2014 that's my data, that's my query!\n\nSo, I wrote some simple Protobuf code to decode the data.\n\n```protobuf\nsyntax = \"proto3\"\n\nmessage Airport {\n    string name = 2;\n}\n\nmessage FlightInfo {\n    string date = 2;\n    Airport dep_airport = 13;\n    Airport arr_airport = 14;\n}\n\nmessage GoogleSucks {\n    repeated FlightInfo = 3;\n}\n```\n\nIt works! Now, I won't consider myself an \"experienced Protobuf developer\" but rather a complete beginner.\n\nI have no idea what I wrote but... it worked! And here it is, `fast-flights`.\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "The fast, robust, strongly-typed Google Flights scraper (API) implemented in Python.",
    "version": "0.3",
    "project_urls": {
        "Bug Tracker": "https://github.com/AWeirdDev/flights/issues",
        "Homepage": "https://github.com/AWeirdDev/flights"
    },
    "split_keywords": [
        "flights",
        " google",
        " google-flights",
        " scraper",
        " protobuf",
        " travel",
        " trip",
        " passengers",
        " airport"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b9e15daa9f7608af9517baa442289fc04845db68dd16da5e086d554bc5b710e9",
                "md5": "5d8a57967d38f2b82d81fd6dfb00dd74",
                "sha256": "972a778af242292d5d14575a2346fbb80d6991795456270793039aa608081cd6"
            },
            "downloads": -1,
            "filename": "fast_flights-0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "5d8a57967d38f2b82d81fd6dfb00dd74",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 48328,
            "upload_time": "2024-05-20T08:33:47",
            "upload_time_iso_8601": "2024-05-20T08:33:47.866096Z",
            "url": "https://files.pythonhosted.org/packages/b9/e1/5daa9f7608af9517baa442289fc04845db68dd16da5e086d554bc5b710e9/fast_flights-0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-20 08:33:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AWeirdDev",
    "github_project": "flights",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "fast-flights"
}
        
Elapsed time: 0.33531s