October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
flight APIs

How to Scrape Google Flights With Python: Fares, Routes, and Times

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For structured Google Flights search results in Python, use a provider that documents a Google Flights search endpoint, such as SerpApi, rather than assuming Google offers a supported public Flights API. Define the route, trip type, dates, and localization; request JSON; then validate the response before extracting itinerary prices, flight legs, airports, and times. The example below uses SerpApi’s documented Python interface, not a Google-published API.

What data can you collect?

A search response is organized around itineraries. An itinerary may include a total price and duration, alongside one or more flight legs. Each leg can provide airline, airport identifiers, and departure and arrival times. The documented response also includes fields such as total_duration and carbon_emissions; optional fields may be absent, so code should not assume every result has every detail.

Results are time-sensitive. Treat a search result as a snapshot, not a guaranteed booking price or inventory commitment. Confirm current airline offer details before making a purchase decision.

How do I scrape Google Flights in Python?

This example follows SerpApi’s documented Python wrapper and Google Flights search interface. It reads the key from an environment variable, calculates future dates, sets a timeout, and handles HTTP, provider, and missing-result cases. It is an illustrative adaptation of the documented interface, not a claim that the code or a particular route was independently tested.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install the wrapper and set your API key

python -m pip install serpapi

Set SERPAPI_KEY in your shell or secret manager; do not commit a real key into source control.

# macOS or Linux shell, for this session only
export SERPAPI_KEY="YOUR_API_KEY"

Run a round-trip search and extract itinerary details

import os
from datetime import date, timedelta

from serpapi import Client

api_key = os.environ.get("SERPAPI_KEY")
if not api_key:
    raise RuntimeError("Set the SERPAPI_KEY environment variable first")

# Replace these IATA airport codes and localization for your search.
outbound_date = date.today() + timedelta(days=30)
return_date = outbound_date + timedelta(days=7)

client = Client(api_key=api_key)
try:
    result = client.search({
        "engine": "google_flights",
        "departure_id": "JFK",
        "arrival_id": "LAX",
        "type": 1,  # round trip; confirm accepted values in current provider docs
        "outbound_date": outbound_date.isoformat(),
        "return_date": return_date.isoformat(),
        "currency": "USD",
        "gl": "us",
        "hl": "en",
    })
except Exception as exc:
    # The wrapper documents HTTP and timeout exceptions; handle them at
    # the application boundary with logging/retry policy appropriate to you.
    raise RuntimeError(f"Google Flights provider request failed: {exc}") from exc

if result.get("error"):
    raise RuntimeError(f"Provider returned an error: {result['error']}")

itineraries = result.get("best_flights") or result.get("other_flights") or []
if not itineraries:
    print("No flight itineraries were returned for this search.")

for itinerary in itineraries:
    print("Price:", itinerary.get("price", "not provided"))
    print("Duration:", itinerary.get("total_duration", "not provided"))
    for leg in itinerary.get("flights", []):
        departure = leg.get("departure_airport") or {}
        arrival = leg.get("arrival_airport") or {}
        print(
            leg.get("airline", "airline not provided"),
            departure.get("id", "airport not provided"),
            departure.get("time", "time not provided"),
            "->",
            arrival.get("id", "airport not provided"),
            arrival.get("time", "time not provided"),
        )

The wrapper’s documented installation and key-handling guidance is in the SerpApi Python wrapper documentation. For current parameter names and conditions, use the Google Flights endpoint and parameter reference and the SerpApi Python travel example. Provider-specific values can change; confirm them against those live references before relying on them.

Which parameters do I need?

A basic airport-pair query needs an origin, destination, trip type, and applicable dates. The documented endpoint uses airport identifiers such as IATA codes in departure_id and arrival_id. It may support other place identifiers; check the provider’s accepted values for the locations you need.

Parameter Purpose Usage notes
departure_id, arrival_id Origin and destination Airport IATA codes are a straightforward example; supported place identifiers depend on provider documentation.
type Trip shape The docs define round trip, one way, and multi-city values. Verify the current accepted value mapping before use.
outbound_date, return_date Travel dates Use YYYY-MM-DD. A return date applies to round trips; one-way and multi-city searches use their respective structures.
gl, hl, currency Country, language, and currency localization These can affect how results are localized or displayed; they do not guarantee identical offers for every user.

One-way and multi-city searches

For a one-way query, set the trip type accordingly and provide the outbound date rather than inventing a return date. For multi-city, the documented format is a JSON list of legs, each with departure, arrival, and date, rather than top-level outbound and return dates. The exact list syntax and accepted values are vendor API details; use the current endpoint reference rather than extrapolating from the round-trip example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Optional filters and passenger settings

The endpoint documentation also describes controls for travel class, passenger counts, sort order, stops, airline inclusion or exclusion, and outbound or return time windows. These are useful when the application needs a constrained search, but a filter can narrow or change returned results. Check the provider’s current accepted parameter values, combinations, and conditions before adding filters to production queries.

How should you validate and parse results?

  1. Check the request outcome. A successful HTTP exchange alone does not establish that useful flight results were returned. Handle transport exceptions, timeouts, and any provider-level error field.
  2. Allow result groups to be absent. The documented Python example checks best_flights and falls back to other_flights. Either group may be missing or empty, so handle both without indexing blindly.
  3. Keep itinerary and leg data distinct. Read itinerary-level fields such as price and total_duration from the itinerary object. Iterate through its flights array for leg-level airline, departure airport, arrival airport, and time information.
  4. Make fields optional in your own model. Use safe lookups for airport IDs, times, airline names, emissions, and other optional attributes. Do not treat a missing value as zero or as evidence that the flight has no such property.
  5. Preserve the query context. Store the route, travel dates, currency, localization, and filters alongside any results you retain. That makes it possible to interpret what a returned fare represents and to refresh the same search later.

If you need normalized output for another service, map provider fields into your own schema while retaining the original response where your data policy allows. Keep amounts paired with their currency and preserve the individual legs instead of reducing a connection itinerary to one departure and arrival pair.

Can you scrape Google Flights directly?

The available documentation supports a managed structured-results workflow; it does not establish a stable public Google Flights page schema or a supported direct page-scraping interface. A script built around requests and BeautifulSoup, or browser automation that reads page markup, should not be assumed to retrieve fares reliably. Page structure and access behavior can change, and a third-party service returning structured results does not by itself establish permission for every intended use.

Google’s Terms of Service, under “Don’t abuse our services,” says users must not use “automated means to access content from any of our services in violation of the machine-readable instructions on our web pages (for example, robots.txt files that disallow crawling, training, or other activities)”. The same list says users must not bypass Google’s systems or protective measures. This is a reminder to respect applicable machine-readable instructions and terms, not a blanket legal conclusion about all scraping or every jurisdiction. Do not make bypassing protective measures a routine part of a scraper.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When is an airline offers API a better fit?

If your goal is to retrieve airline offers for an application or support a booking flow, an airline offers API may fit better than reproducing a Google Flights search. Duffel documents creating an offer request from passengers and journey slices, then receiving offers from a range of airlines. That is a different sourcing and integration model, not a drop-in Google Flights replica; coverage and returned offers should not be assumed identical.

Duffel notes that search results can be incomplete within a supplier timeout, and its offer documentation says prices and service details can change. Refresh offer details when a traveler is considering booking rather than presenting a search-time price as guaranteed at purchase. Compare options based on Google-specific coverage, airline sourcing and booking support, route/date and passenger filters, integration effort, and refresh behavior. See Duffel Offer Requests and Duffel Offers.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For website screenshots—not structured flight-search data—ScreenshotNeo is a website screenshot API and MCP server. It is not a Google Flights data API, so use the workflow above when you need itinerary fares, routes, and times. For a page capture, one GET request can return PNG, JPEG, WebP, or PDF. The example below uses the ScreenshotNeo endpoint and documents its parameters at ScreenshotNeo docs.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers indicating the page verdict and billing. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting

The script says the API key is missing

Confirm that SERPAPI_KEY is set in the same shell or process environment that launches Python. Restart the process after changing environment settings, and keep the secret out of committed code.

The request times out or raises an HTTP exception

The wrapper documents HTTP and timeout exceptions. Catch them at the boundary of your application, log enough context to diagnose the failure without logging secrets, and use a bounded retry policy appropriate to your use case. A retry should not become an unbounded loop.

The response is valid JSON but has no itineraries

Check for a provider error first, then inspect whether both best_flights and other_flights are absent or empty. Verify airport identifiers, trip type, dates, and filters against the endpoint reference. A successful HTTP response does not guarantee results.

A field is missing from one result

Optional itinerary and leg fields are not guaranteed on every result. Use dictionary .get() lookups, represent unavailable values explicitly in your own output, and avoid code that assumes every leg has identical metadata.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The displayed fare is no longer available

Search results are time-sensitive. Refresh the search or offer details and confirm the current airline terms before a booking decision; do not promise that a previously returned price remains available.

Frequently Asked Questions

Does Google provide the API used in this example?

No. The example calls SerpApi’s documented Google Flights search interface; it is not a Google-published Flights API.

Can I use the returned price as a guaranteed booking quote?

No. Treat it as a search result and confirm current airline offer details before booking.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.