Skip to main content
TutorialsNovember 24, 2026 · 14 min read

How to use a web search API with Python

Call a web search API from Python, filter and page through results, and save clean records without inventing missing fields.

How to use a web search API with Python

You need search results inside a script or an app, but you don't have the URLs yet. A web search API gives you titles, links and descriptions as JSON, so there's no results page to parse. This tutorial uses Spidra Search from Python to build search.py, a command that runs a query, filters and pages through the results, and saves one clean record per result without filling in anything the API didn't return.

Run your first search

Install the SDK with pip install spidra (Python 3.9 or later) and put your key in SPIDRA_API_KEY. search() waits for the answer, so you get the results back directly:

# first_search.py
import os
from spidra import Spidra

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
first = client.search("best espresso machine", sources=["web"], limit=3)
for r in first.data.web:
    print(r.position, r.title, "|", r.url)

Output:

1 The 16 Best Espresso Machines of 2026, Tested & Reviewed | https://www.seriouseats.com/best-espresso-machines-5185482
2 Best Espresso Machines 2026 | Tested - Forbes Vetted | https://www.forbes.com/sites/forbes-personal-shopper/article/best-espresso-machine/
3 The 7 best espresso machines you can buy in 2026 - Tom's Guide | https://www.tomsguide.com/home/coffee-makers/best-espresso-machines

Each source comes back as its own list under first.data, and limit applies per source. Nothing is summarized or rewritten, so the titles and descriptions are what the search found.

Results from different sources carry different fields

Search covers six sources: web, news, images, videos, research (arXiv and PubMed among others) and developer (GitHub issues and pull requests). Every result has a title, a URL and a position. The rest depends on the source, so check which fields are empty before you rely on them:

# missing_fields.py  (client as before)
result = client.search("vector database", sources=["news", "research", "developer"], limit=1)

OPTIONAL = ("description", "source", "date", "authors", "doi")
for source in ("news", "research", "developer"):
    item = getattr(result.data, source)[0]
    print(source.ljust(10), [f for f in OPTIONAL if getattr(item, f) is None])

Output:

news       ['authors', 'doi']
research   []
developer  ['doi']

A field the source doesn't have comes back as None. Fields also come and go inside one source, so one news result can name its outlet while the next doesn't. News dates are relative text such as "3 years ago", while research and developer dates are ISO.

Turn each result into a record without filling gaps

The tempting cleanup is a default: the title as the description, a parsed date for "3 years ago", an empty string for a blank. This Hit keeps what the API returned and leaves everything else None:

# hits.py
import html
from dataclasses import dataclass
from typing import Optional
from urllib.parse import urlsplit


@dataclass(frozen=True)
class Hit:
    query: str
    source_type: str                  # web, news, images, videos, research or developer
    position: int                     # the rank the API gave it
    title: Optional[str]
    url: str
    description: Optional[str] = None
    publisher: Optional[str] = None   # the API's `source`: a news outlet, "arXiv", "GitHub"
    date_text: Optional[str] = None   # exactly as returned: "3 years ago" or "2024-03-08"
    authors: Optional[str] = None
    doi: Optional[str] = None
    domain: str = ""                  # derived from the url
    retrieved_at: str = ""            # when we fetched it, not when it was published

clean() turns a missing or blank value into None, and to_hit() builds the record. A result with no URL is dropped, because there's nothing to open or de-duplicate on:

def clean(value):
    """Decode HTML entities and trim. A missing or blank field becomes None, never a stand-in."""
    if value is None:
        return None
    text = html.unescape(value).strip()
    return text or None


def to_hit(item, query, source_type, retrieved_at):
    url = (item.url or "").strip()
    if not url:
        return None
    return Hit(
        query=query, source_type=source_type, position=item.position,
        title=clean(item.title), url=url,
        description=clean(item.description), publisher=clean(item.source),
        date_text=clean(item.date), authors=clean(item.authors), doi=clean(item.doi),
        domain=urlsplit(url).hostname or "", retrieved_at=retrieved_at,
    )

html.unescape is there because some descriptions arrive with entities in them, such as don't. publisher is the API's source field renamed, so it can't be confused with source_type. domain comes from the URL and retrieved_at is ours, and both are labelled as such. These tests pin the rules:

# test_hits.py
from types import SimpleNamespace as NS

from spidra import SpidraRateLimitError

import search
from hits import dedupe, to_hit

NOW = "2026-11-24T12:00:00+00:00"


def item(**fields):
    base = dict(title="A title", url="https://example.com/a", position=1, description=None,
                source=None, date=None, authors=None, doi=None)
    return NS(**(base | fields))


def test_missing_fields_stay_none():
    hit = to_hit(item(), "q", "web", NOW)
    assert hit.description is None and hit.publisher is None and hit.doi is None
    assert hit.title == "A title"          # the title is not copied into the description



def test_html_entities_are_decoded():
    hit = to_hit(item(description="Vector databases don't get as much love"), "q", "news", NOW)
    assert hit.description == "Vector databases don't get as much love"


def test_a_relative_date_is_kept_as_text():
    assert to_hit(item(date="3 years ago"), "q", "news", NOW).date_text == "3 years ago"


def test_a_result_without_a_url_is_dropped():
    assert to_hit(item(url=""), "q", "web", NOW) is None
    assert to_hit(item(url=None), "q", "web", NOW) is None

Filter the results

Four filters cover most needs: include_domains or exclude_domains (never both), time_range to favor recent pages, country to localize, and filetype="pdf" for documents. Domain filters are checked against each result before it comes back, and filetype returns only files of that type. This search asks for PDFs:

# client as before
reports = client.search("annual report 2025 renewable energy", sources=["web"], filetype="pdf", limit=5)
for r in reports.data.web:
    print(r.title, "|", r.url)

Output:

PDF Annual Report 2025 | https://europeanenergy.com/wp-content/uploads/2026/02/annual-report-2025.pdf
PDF RWE_Annual Report_2025 | https://www.rwe.com/-/media/RWE/documents/05-investor-relations/finanzkalendar-und-veroeffentlichungen/2025-GJ/RWE_Annual-Report_2025.pdf
PDF Annual Report 2025 - cdn.orsted.com | https://cdn.orsted.com/-/media/annual-2025/annual-report-2025.pdf
PDF ANNUAL REPORT 2025 - metisenergy.com | https://metisenergy.com/wp-content/uploads/METIS_ENERGY_AR2025.pdf
PDF BEP 2025 Annual Report | https://bep.brookfield.com/sites/brookfield-bep-v2/files/Brookfield-BEP-IR-V2/annual-reports/bep-2025-annual-report.pdf

time_range and country shape the results but don't guarantee them, so treat them as preferences. Filters also apply to some sources only: domain filters and filetype don't apply to research or developer, and a source that can't apply a filter runs without it. The API reference lists more filters, such as date ranges and language. The Python SDK doesn't accept all of them yet, so call the REST endpoint directly for those.

A narrow query can return no PDFs at all, which is an empty search and not an error.

Page through the results

A finished search returns one token per source that has more results. Pass the tokens back as page_tokens with the same query and options:

# client as before
first = client.search("python web scraping tutorial", sources=["web"], limit=5)
for r in first.data.web:
    print(r.position, r.title, "|", r.url)

second = client.search(
    "python web scraping tutorial",
    sources=["web"],
    limit=5,
    page_tokens=first.data.next_page_tokens,
)

seen = {r.url for r in first.data.web}
new = [r for r in second.data.web if r.url not in seen]
print(f"page 2: {len(second.data.web)} results, {len(new)} new")
for r in new[:3]:
    print(r.position, r.title, "|", r.url)

Output:

1 Python Web Scraping Tutorial - GeeksforGeeks | https://www.geeksforgeeks.org/python/python-web-scraping-tutorial/
2 A Practical Introduction to Web Scraping in Python | https://realpython.com/python-web-scraping-practical-introduction/
3 Python Web Scraping Tutorial - Online Tutorials Library | https://www.tutorialspoint.com/python_web_scraping/index.htm
4 Python Web Scraping Tutorials | https://realpython.com/tutorials/web-scraping/
5 Python Web Scraping Tutorial: Complete Guide (2025) | https://generalistprogrammer.com/tutorials/python-web-scraping-tutorial-complete-guide
page 2: 5 results, 5 new
6 Python Web Scraping (Learning Path) - Real Python | https://realpython.com/learning-paths/python-web-scraping/
7 Beautiful Soup: Build a Web Scraper With Python | https://realpython.com/beautiful-soup-web-scraper-python/
8 Python Web Scraping: Step-By-Step Tutorial - ScraperAPI | https://www.scraperapi.com/web-scraping/python/

With tokens, page 2 continues the numbering at 6 and the same result set carries on past page 5, which a plain page number can't do. A URL from page 1 can occasionally come back on page 2, so de-duplicate by URL. Each extra page is billed like a new search.

Here is the loop behind search.py, with its imports. It calls search_with_backoff, defined in the next section. It stops when there are no tokens, and from the second page on it only asks the sources that still have results, because a source sent without a token starts over:

# search.py
import argparse
import json
import os
import time
from dataclasses import asdict
from datetime import datetime, timezone

from spidra import Spidra, SpidraRateLimitError

from hits import FIELDS, coverage, dedupe, to_hit

SOURCES = ["web", "news", "images", "videos", "research", "developer"]


def collect(client, query, sources, limit, pages, **filters):
    """Fetch up to `pages` pages per source, following page tokens. Returns (hits, repeats, dropped)."""
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    hits, dropped, tokens = [], 0, None
    for _ in range(pages):
        options = dict(filters, sources=sources, limit=limit)
        if tokens:
            options["page_tokens"] = tokens
        result = search_with_backoff(client, query, **options)
        for source in sources:
            for item in getattr(result.data, source) or []:
                hit = to_hit(item, query, source, now)
                if hit:
                    hits.append(hit)
                else:
                    dropped += 1
        tokens = result.data.next_page_tokens
        if not tokens:
            break
        sources = [s for s in sources if s in tokens]   # a source with no token has no more results
    unique = dedupe(hits)
    return unique, len(hits) - len(unique), dropped

dedupe() goes in hits.py. It keeps one record per source and URL, so a page that appears in both web and news is kept in each:

def dedupe(hits):
    seen, kept = set(), []
    for hit in hits:
        key = (hit.source_type, hit.url)
        if key not in seen:
            seen.add(key)
            kept.append(hit)
    return kept

The paging tests use a hand-written client, so they check the logic and not the API:

class FakeClient:
    """Hand-written pages for testing the paging logic. Not API output."""
    def __init__(self, pages):
        self.pages, self.calls = list(pages), []

    def search(self, query, **options):
        self.calls.append(options)
        return self.pages.pop(0)


def page(tokens=None, **lists):
    return NS(data=NS(**({"next_page_tokens": tokens, "web": None, "news": None} | lists)))


def test_the_same_url_is_kept_once_per_source():
    web, news = to_hit(item(), "q", "web", NOW), to_hit(item(), "q", "news", NOW)
    assert dedupe([web, web, news]) == [web, news]


def test_later_pages_only_ask_for_sources_that_have_more():
    first = page({"web": "t1"}, web=[item()], news=[item(url="https://example.com/n")])
    second = page(None, web=[item(url="https://example.com/b", position=2)])
    client = FakeClient([first, second])
    hits, repeats, dropped = search.collect(client, "q", ["web", "news"], 10, 3)
    assert client.calls[1]["sources"] == ["web"] and client.calls[1]["page_tokens"] == {"web": "t1"}
    assert len(hits) == 3 and len(client.calls) == 2

Handle empty searches, failures and rate limits

A search that finds nothing still completes, with success: false and empty lists, and it costs nothing. collect() already copes, because it reads each list with or [].

A search that fails raises SpidraJobFailedError and isn't charged. A bad request, such as a limit over 20, raises SpidraValidationError with the reasons in errors. Don't retry either one unchanged.

Searches are limited to 60 requests a minute and 10 unfinished at once. The SDK retries temporary server errors (502, 503 and 504) for you, but a 429 is yours to handle. SpidraRateLimitError carries retry_after, so wait that long and try again:

def search_with_backoff(client, query, tries=4, **options):
    for attempt in range(tries):
        try:
            return client.search(query, **options)
        except SpidraRateLimitError as error:
            if attempt == tries - 1:
                raise
            time.sleep(error.retry_after or 2 ** (attempt + 1))

The test fakes a 429 that asks for 7 seconds and checks that the code waits exactly that long:

def test_backoff_waits_the_time_the_api_asks_for(monkeypatch):
    waits = []
    monkeypatch.setattr(search.time, "sleep", waits.append)
    ok = page(None, web=[])

    class Limited(FakeClient):
        def search(self, query, **options):
            if not self.calls:
                self.calls.append(options)
                raise SpidraRateLimitError("slow down", retry_after=7)
            return super().search(query, **options)

    assert search.search_with_backoff(Limited([ok]), "q") is ok
    assert waits == [7]

Save the records and run the command

The last piece counts which optional fields each source left empty, so gaps are visible in the output and not hidden in the file. Add coverage() to hits.py:

FIELDS = ("description", "publisher", "date_text", "authors", "doi")


def coverage(hits):
    """For each source, how many hits there are and how many have each optional field."""
    rows = {}
    for hit in hits:
        row = rows.setdefault(hit.source_type, {"hits": 0, **{f: 0 for f in FIELDS}})
        row["hits"] += 1
        for field in FIELDS:
            row[field] += getattr(hit, field) is not None
    return rows

Then main() in search.py reads the options, collects the hits and writes one JSON line per result:

def main(client, argv=None):
    ap = argparse.ArgumentParser(description="Search the web with Spidra and save normalized results.")
    ap.add_argument("query")
    ap.add_argument("--source", action="append", choices=SOURCES, dest="sources")
    ap.add_argument("--limit", type=int, default=10)
    ap.add_argument("--pages", type=int, default=1)
    domains = ap.add_mutually_exclusive_group()
    domains.add_argument("--include", nargs="+", dest="include_domains")
    domains.add_argument("--exclude", nargs="+", dest="exclude_domains")
    ap.add_argument("--time-range", choices=["hour", "day", "week", "month", "year"], dest="time_range")
    ap.add_argument("--filetype", choices=["pdf"])
    ap.add_argument("--out", default="results.jsonl")
    args = ap.parse_args(argv)

    names = ("include_domains", "exclude_domains", "time_range", "filetype")
    filters = {name: getattr(args, name) for name in names if getattr(args, name)}
    hits, repeats, dropped = collect(client, args.query, args.sources or ["web"], args.limit, args.pages, **filters)

    with open(args.out, "w", encoding="utf-8") as out:
        for hit in hits:
            out.write(json.dumps(asdict(hit), ensure_ascii=False) + "\n")
            print(hit.source_type.ljust(9), hit.position, hit.title, "|", hit.url)
    print(f"saved {len(hits)} hits to {args.out} ({repeats} repeats removed, {dropped} without a URL)")
    for source, row in coverage(hits).items():
        missing = {f: row["hits"] - row[f] for f in FIELDS if row["hits"] - row[f]}
        print(source.ljust(9), row["hits"], "hit(s), missing:", missing or "nothing")


if __name__ == "__main__":
    main(Spidra(api_key=os.environ["SPIDRA_API_KEY"]))

Run the tests first:

$ pytest -q
.......                                                                  [100%]
7 passed in 0.08s

Then run a web search:

$ python search.py "best espresso machine" --limit 3

Output:

web       1 The 16 Best Espresso Machines of 2026, Tested & Reviewed | https://www.seriouseats.com/best-espresso-machines-5185482
web       2 Best Espresso Machines 2026 | Tested - Forbes Vetted | https://www.forbes.com/sites/forbes-personal-shopper/article/best-espresso-machine/
web       3 The 7 best espresso machines you can buy in 2026 - Tom's Guide | https://www.tomsguide.com/home/coffee-makers/best-espresso-machines
saved 3 hits to results.jsonl (0 repeats removed, 0 without a URL)
web       3 hit(s), missing: {'publisher': 3, 'date_text': 3, 'authors': 3, 'doi': 3}

Web results carry no date, outlet, authors or DOI, and the report says so. Now three sources at once:

$ python search.py "vector database" --source news --source research --source developer --limit 1

Output:

news      1 VCs are obsessed with vector databases. Here are seven AI startups in the space that have raised millions from investors. | https://www.businessinsider.com/seven-vector-database-startups-poised-to-win-ai-revolution-2024-4
research  1 BioVDB: biological vector database for high-throughput gene expression meta-analysis. | https://doi.org/10.3389/frai.2024.1366273
developer 1 PR: feat(vector-db): add Qdrant vector database support (#273) | https://github.com/arakoodev/EdgeChains/pull/706
saved 3 hits to results.jsonl (0 repeats removed, 0 without a URL)
news      1 hit(s), missing: {'authors': 1, 'doi': 1}
research  1 hit(s), missing: nothing
developer 1 hit(s), missing: {'doi': 1}

This is the first line of results.jsonl. The news description has its entity decoded, the date is still the text the API gave, and the authors and DOI are null, not empty strings:

{"query": "vector database", "source_type": "news", "position": 1, "title": "VCs are obsessed with vector databases. Here are seven AI startups in the space that have raised millions from investors.", "url": "https://www.businessinsider.com/seven-vector-database-startups-poised-to-win-ai-revolution-2024-4", "description": "Vector databases don't get as much love as their flashier counterparts ...", "publisher": "Business Insider", "date_text": "3 years ago", "authors": null, "doi": null, "domain": "www.businessinsider.com", "retrieved_at": "2026-11-24T12:49:23+00:00"}

Read the pages when snippets aren't enough

A description is a snippet of the page. To get the page text itself, add scrape_options and each of the top web results comes back with its content as Markdown:

# client as before
from spidra import SearchScrapeOptions

results = client.search(
    "how does retrieval augmented generation work",
    sources=["web"],
    limit=3,
    scrape_options=SearchScrapeOptions(formats=["markdown"], max_results=3),
)

for r in results.data.web:
    text = (r.markdown or "").strip()
    print(r.title, "|", r.url)
    print(f"  {len(text)} characters of page content")

Output:

What is RAG? - Retrieval-Augmented Generation AI Explained - AWS | https://aws.amazon.com/what-is/retrieval-augmented-generation/
  21578 characters of page content
What is Retrieval-Augmented Generation (RAG) - GeeksforGeeks | https://www.geeksforgeeks.org/nlp/what-is-retrieval-augmented-generation-rag/
  16296 characters of page content
What is retrieval augmented generation (RAG)? - IBM | https://www.ibm.com/think/topics/retrieval-augmented-generation
  18717 characters of page content

This search takes as long as its slowest page, so expect it to be slower than a plain one. A page that can't be fetched just has no markdown, and the other results are unaffected. For specific fields instead of whole pages, pass the URLs to batch scrape with a schema, as in the guide to extracting consistent JSON from different websites.

What this approach doesn't cover

  • Results change over time, so the same query can return different pages next week. Keep retrieved_at and the query with each record.
  • A description is a snippet, not the page, and a search finds pages without checking what they claim.
  • time_range and country are preferences, not guarantees.
  • This command writes one file per run. Add a database or merge step if you need to keep results across runs.
  • If you're choosing between search APIs, or moving off one, our posts on the best web search APIs for AI agents and the Google Custom Search API shutdown cover that decision.

Conclusion

You now have a command that turns a query into clean records: filtered, paged, de-duplicated, with missing fields left missing and a report of what each source left out. Spidra Search is what keeps it short:

  • Search before you have URLs. One call covers web, news, images, videos, research papers and GitHub, and each source comes back as its own list, so an empty source doesn't fail the others.
  • Filters that are checked. Domain filters are verified against each result before it comes back, and a PDF filter returns only PDFs.
  • From a query to page text in one call. scrape_options reads the top results and adds each page as Markdown, and a page that can't be read doesn't stop the rest.
  • The next step is already there. The same account and SDK scrape, batch scrape with a schema, crawl and parse, so search results turn into structured data without a second vendor or a second bill.
  • Nothing to pay for when nothing comes back. Searches that find nothing or fail aren't charged.

Every plan has every feature, and the dashboard's Code button writes the request for whatever you set up. Create a free account (300 credits, no card required), set SPIDRA_API_KEY, and run search.py with your own query.

Frequently asked questions

Install the Spidra SDK, create a client with your API key, and call search with a query. The result has one list per source, and each item has a title, a URL, a description and a position. Add filters or page tokens to narrow or continue the results.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.