DEV Community

Cover image for Google Flights search URLs are a base64 protobuf. Here's how to build one in Python
Hugues Ishema
Hugues Ishema

Posted on Fully Autonomous

Google Flights search URLs are a base64 protobuf. Here's how to build one in Python

TL;DR: The tfs= blob in a Google Flights URL is URL-safe base64 wrapped around a protobuf message. Legs, airports, dates, passengers, cabin and trip type are plain protobuf fields. You can decode one with about 30 lines of Python and no .proto file, and build your own with 30 more. I checked mine against a real search on 24 November 2026: the URL my Python built was byte-for-byte the one our scraper fetched, and it returned 32 flights from $406.

The question with 11,000 views

"How can I decode/recreate Google Flights Search URLs?" was asked on Stack Overflow in August 2021. It had 10,995 views when I checked on 24 November 2026. The asker had already guessed base64 and could read "HNL" and "2021-09-13" in the decoded bytes, but not the rest.

The accepted answer sidesteps the question: use ?q=Flights to SFO from HNL on ... and let Google parse the sentence. That's handy for a link in an email. It's not something I'd put in code, because you're depending on Google's natural-language parser instead of a structure. I didn't test it for this post.

Why people want this at all: Google had a flight-search API, QPX Express, and shut it down on 10 April 2018, citing "low interest among our travel partners". There's no public Google Flights API today. The URL is the closest thing to an interface.

Question Answer (checked 24 Nov 2026)
Official Google Flights API? No. QPX Express closed in April 2018
Is tfs documented? No. Everything below is reverse-engineered
Can you build a valid tfs without a .proto file? Yes. The wire format is enough
Does Google return prices for a minimal hand-built tfs? Yes, in my test (32 flights, JFK-LAX round trip)

Decoding the Stack Overflow URL

Protobuf's wire format is simple. Every field is a varint key (field_number << 3 | wire_type) followed by either a varint (type 0) or a length and raw bytes (type 2). Nested messages are just bytes that decode the same way. So a decoder that doesn't know the schema can still print the tree:

import base64

def read_varint(b, i):
    shift = n = 0
    while True:
        byte = b[i]; i += 1
        n |= (byte & 0x7F) << shift
        shift += 7
        if byte < 0x80:
            return n, i

def decode(b, depth=0):
    i = 0
    while i < len(b):
        key, i = read_varint(b, i)
        field, wire = key >> 3, key & 7
        pad = "  " * depth
        if wire == 0:
            v, i = read_varint(b, i)
            print(f"{pad}{field}: {v}")
        elif wire == 2:
            n, i = read_varint(b, i)
            chunk = b[i:i + n]; i += n
            try:
                text = chunk.decode()
                if text.isprintable():
                    print(f'{pad}{field}: "{text}"'); continue
            except UnicodeDecodeError:
                pass
            print(f"{pad}{field} {{"); decode(chunk, depth + 1); print(f"{pad}}}")
        else:
            raise ValueError(f"wire type {wire} at byte {i}")

def decode_tfs(tfs):
    decode(base64.urlsafe_b64decode(tfs + "=" * (-len(tfs) % 4)))
Enter fullscreen mode Exit fullscreen mode

Feed it the tfs from the question (HNL to SFO, 13 to 17 September 2021):

1: 28
2: 2
3 {
  13 {
    1: 1
    2: "HNL"
  }
  2: "2021-09-13"
  14 {
    1: 1
    2: "SFO"
  }
}
3 {
  13 {
    1: 1
    2: "SFO"
  }
  2: "2021-09-17"
  14 {
    1: 1
    2: "HNL"
  }
}
14: 1
16 {
  1: 18446744073709551615
}
8: 1
9: 1
19: 1
Enter fullscreen mode Exit fullscreen mode

The "whitespace" the asker couldn't read was field keys and lengths. The field meanings below come from the flights.proto in fast-flights (MIT, 2,138 stars, last commit 15 November 2026, about 119,000 PyPI downloads last month), and our scraper has used the same numbers against live results since October:

Field Meaning Values
3 (repeated) One flight leg 1 leg = one-way, 2 = round trip
3.2 Date "YYYY-MM-DD"
3.5 Max stops 0 = nonstop
3.13 / 3.14 From / to message with 2 = code
3.13.1 Place type 1 = airport code; an example URL in another answer uses 2 with a Freebase city ID like /m/02_286
8 (repeated) One passenger each 1 adult, 2 child, 3 infant in seat, 4 infant on lap
9 Cabin 1 economy, 2 premium economy, 3 business, 4 first
19 Trip type 1 round trip, 2 one-way
1, 2, 14, 16 Not needed Not in fast-flights' schema either. I left them out and Google still answered. 16.1 set to 2^64-1 looks like "no limit", but that's a guess

fast-flights maps more than this: airlines (3.6), departure and arrival hour windows, max duration, layover limits, max price (12) and bags (13). If you only need Python and are fine parsing the page yourself, use it. The point of writing the encoder by hand is that it fits in any language and you can see every byte.

Building one

Encoding is the same thing in reverse:

import base64

def _varint(n):
    out = bytearray()
    while n > 0x7F:
        out.append((n & 0x7F) | 0x80)
        n >>= 7
    out.append(n)
    return bytes(out)

def _int(field, value):          # wire type 0
    return _varint(field << 3) + _varint(value)

def _bytes(field, data):         # wire type 2
    if isinstance(data, str):
        data = data.encode()
    return _varint(field << 3 | 2) + _varint(len(data)) + data

SEAT = {"economy": 1, "premium_economy": 2, "business": 3, "first": 4}

def build_tfs(legs, adults=1, seat="economy", max_stops=None):
    """legs: [("2026-12-11", "JFK", "LAX"), ...]; 1 leg = one-way, 2 = round trip."""
    msg = b""
    for date, frm, to in legs:
        leg = _bytes(2, date)
        if max_stops is not None:
            leg += _int(5, max_stops)
        leg += _bytes(13, _bytes(2, frm)) + _bytes(14, _bytes(2, to))
        msg += _bytes(3, leg)
    msg += _int(8, 1) * adults                      # 1 = adult passenger
    msg += _int(9, SEAT[seat])
    msg += _int(19, 1 if len(legs) == 2 else 2)     # 1 = round trip, 2 = one-way
    return base64.urlsafe_b64encode(msg).rstrip(b"=").decode()

def flights_url(tfs, hl="en", gl="us", curr="USD"):
    return f"https://www.google.com/travel/flights/search?tfs={tfs}&hl={hl}&gl={gl}&curr={curr}"
Enter fullscreen mode Exit fullscreen mode

JFK to LAX, 11 to 18 December 2026, one adult, economy:

https://www.google.com/travel/flights/search?tfs=GhoSCjIwMjYtMTItMTFqBRIDSkZLcgUSA0xBWBoaEgoyMDI2LTEyLTE4agUSA0xBWHIFEgNKRktAAUgBmAEB&hl=en&gl=us&curr=USD
Enter fullscreen mode Exit fullscreen mode

That is the exact URL the scraper fetched in the run below. Change hl, gl and curr for language, country and currency. Note that rstrip(b"=") matters: Google's URLs drop the base64 padding.

Getting the prices behind the URL

A URL is half the job. The prices load in the page, and requesting Google Flights in a loop from one IP gets you blocked quickly. I didn't test it from my own machine for that reason.

This runs on Apify instead (apify-client 3.x). The Actor builds the same tfs, fetches the page through rotating proxies and parses it:

import os
from apify_client import ApifyClient
from tfs import build_tfs, flights_url

# 1. The URL you would build yourself
mine = flights_url(build_tfs([("2026-12-11", "JFK", "LAX"), ("2026-12-18", "LAX", "JFK")]))

# 2. The prices behind that URL, fetched on Apify
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("kuezi/google-flights-scraper").call(run_input={
    "routes": ["JFK-LAX 2026-12-11 2026-12-18"],
    "maxFlightsPerSearch": 5,
})
flights = client.dataset(run.default_dataset_id).list_items().items

for f in flights:
    print(f["rank"], f["price"], f["flightNumbers"], f["departure"], f["stops"], f["priceLevel"])
print("same URL as mine:", flights[0]["googleFlightsUrl"] == mine)

search = client.key_value_store(run.default_key_value_store_id).get_record("SUMMARY")["value"]["searches"][0]
print("found", search["flightsFound"], "| typical", search["typicalPriceLow"], "-", search["typicalPriceHigh"],
      "|", len(search["priceHistory"]), "days of price history")
Enter fullscreen mode Exit fullscreen mode

Real output (24 November 2026, run took 4 seconds):

1 406 ['B6 2223'] 2026-12-11T08:01 0 typical
2 406 ['B6 623'] 2026-12-11T09:00 0 typical
3 406 ['B6 223'] 2026-12-11T10:00 0 typical
4 406 ['B6 323'] 2026-12-11T11:00 0 typical
5 406 ['B6 723'] 2026-12-11T13:59 0 typical
same URL as mine: True
found 32 | typical 382 - 600 | 61 days of price history
Enter fullscreen mode Exit fullscreen mode

same URL as mine: True is the check that matters here: the hand-built tfs is exactly what produced those 32 flights. Each row also carries airlines, arrival time, duration, layovers, aircraft, legroom and CO2 emissions. priceLevel and the typical range are Google's own "prices are currently typical" box.

Google Flights Scraper on Apify. Disclosure: I built this. It charges $0.003 per route search that returns flights plus $0.0005 per flight saved, so this run cost $0.0055. Empty and failed searches are free. It can also scan up to 90 departure days and report the cheapest day.

Limits, honestly

  • Undocumented. Google can change the field numbers tomorrow. If it does, every tfs builder breaks, mine included.
  • The URL isn't the data. It opens a search. You still need to fetch and parse the page, and that's the part that breaks and gets blocked.
  • No booking. You get prices and itineraries, not tickets. For booking you need an airline or GDS deal.
  • Cities need different IDs. Plain airport codes work (my encoder leaves the place type out). "All London airports" uses a Freebase-style city ID, which I haven't mapped.
  • Prices move. The output above is a snapshot from 24 November 2026.

If you've mapped fields 1, 2, 14 or 16, tell me in the comments and I'll update the table.

AI disclosure: I wrote this with AI assistance. Every number and output above was checked or run on 24 November 2026.

Top comments (2)

Collapse
 
jun_liu_ca219b73a8f1489b5 profile image
jun liu •

Great write-up — the param-order sensitivity and the opaque 'tfs' segment are exactly the two traps I'd warn about. If you're wrapping this in a scraper, keep the URL shape byte-stable and validate the decoded protobuf against one live search before you trust any price, because the encoding changes between UI releases. Logging the exact URL you send also makes it much faster to spot when a rule silently breaks.

Collapse
 
lilithbrown profile image
Lilith Brown •

Base64 in a query string is a wire format pretending to be a parameter, and it stays readable right up until it doesn't. The one addition I'd make to the round-trip: store the decoded message next to the URL, not just the encoded string. When the schema moves, re-encoding from your own model silently drops whatever you didn't parse, while the original bytes still carry it.

And if you're parsing rather than just templating it, log the field numbers you actually see. A new field showing up is the early warning that the URL shape is about to change — much cheaper than finding out when the results come back different.