Skip to main content
TutorialsNovember 30, 2026 · 12 min read

How to build a multi-source news research dashboard

Build a small dashboard on a search API: run news and web searches, handle missing dates and thumbnails, store every query and compare the sources.

How to build a multi-source news research dashboard

You want a small dashboard that collects news and web results for the topics you follow: a link for each result, a date when there is one, a source label, and a box to search what you've saved. This tutorial builds that news research dashboard on a search API, using Python, FastAPI and SQLite. By the end you can run a query for a topic, see what each source type returned, and come back to everything you've stored.

The dashboard is query-driven: results change only when you run a search, and nothing in it refreshes on a schedule. If you haven't used the Spidra Python SDK before, the Python tutorial covers the install and your API key.

preview-SAMPLE-DATA-not-for-the-article.png

Set up the project

Install the three packages and set your key:

pip install fastapi uvicorn spidra
export SPIDRA_API_KEY=spd_YOUR_API_KEY

The project is six files, each with one job:

newsboard/
├── first_search.py   the first search call, run on its own
├── app.py            FastAPI routes and the search call
├── normalize.py      one shape for every result
├── store.py          SQLite: topics, runs, results
├── demo_data.py      invented sample data for previews
└── static/index.html the whole interface

Run one search for news and web

Spidra Search takes a query and a list of sources, and returns structured results with nothing summarized or rewritten. Each source runs on its own, so a source with no results doesn't fail the other.

# first_search.py
import os

from spidra import Spidra

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
result = client.search("EU AI Act implementation", sources=["news", "web"], limit=5)

for kind in ("news", "web"):
    for item in getattr(result.data, kind) or []:
        print(kind, item.position, item.date, item.source, item.title[:60])

The fields differ by source. Web results carry a title, link, description and position. News results add a date, and sometimes a source name and a thumbnail. Everything after this section exists because those optional fields are not always there.

Normalize the optional metadata

The interface shouldn't check for missing fields on every card, so we flatten every result into one shape before it's stored. News dates often arrive as relative text ("3 days ago"), so the first job is turning them into something sortable, as an estimate.

SECONDS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400, "week": 604800, "month": 2592000, "year": 31536000}
DATE_FORMATS = ("%Y-%m-%d", "%b %d, %Y", "%B %d, %Y", "%d %b %Y", "%d %B %Y")


def parse_date(text, now):
    """Turn a result's date text into an ISO timestamp, or None if it can't be read.

    News dates often arrive as relative text ("3 days ago"), so the result is an estimate.
    """
    if not text:
        return None
    value = text.strip().lower()
    match = re.match(r"(\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago", value)
    if match:
        delta = timedelta(seconds=int(match[1]) * SECONDS[match[2]])
        return (now - delta).isoformat(timespec="minutes")
    if value == "yesterday":
        return (now - timedelta(days=1)).isoformat(timespec="minutes")
    for fmt in DATE_FORMATS:
        try:
            return datetime.strptime(text.strip(), fmt).replace(tzinfo=timezone.utc).isoformat(timespec="minutes")
        except ValueError:
            pass
    try:
        parsed = datetime.fromisoformat(text.strip().replace("Z", "+00:00"))
        return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).isoformat(timespec="minutes")
    except ValueError:
        return None

Run it on a few inputs, with a fixed "now" so the output stays the same:

from datetime import datetime, timezone
from normalize import parse_date

now = datetime(2026, 11, 20, 12, 0, tzinfo=timezone.utc)
for text in ["3 days ago", "2 hours ago", "Nov 12, 2026", "2026-11-18T09:30:00Z", "sometime recently", None]:
    print(repr(text), "->", parse_date(text, now))
'3 days ago' -> 2026-11-17T12:00+00:00
'2 hours ago' -> 2026-11-20T10:00+00:00
'Nov 12, 2026' -> 2026-11-12T00:00+00:00
'2026-11-18T09:30:00Z' -> 2026-11-18T09:30+00:00
'sometime recently' -> None
None -> None

A date that can't be read becomes None, and the original text is kept next to it so the card can still show it.

Two more fields need a fallback. A result without a source name gets the domain of its link, and a thumbnail is kept only if it's a real web address:

def domain_of(url):
    host = urlparse(url).netloc.lower()
    return host[4:] if host.startswith("www.") else host


def usable_image(url):
    """Keep only real image addresses. Some sources return IDs or nothing."""
    return url if url and url.startswith(("http://", "https://", "/demo-thumb/")) else None
for u in ["https://img.example.com/a.jpg", "5f3a-internal-id", None]:
    print(repr(u), "->", usable_image(u))
'https://img.example.com/a.jpg' -> https://img.example.com/a.jpg
'5f3a-internal-id' -> None
None -> None

normalize_results does this for every news and web result and skips any link that isn't http or https:

def normalize_results(data, now):
    """Flatten SDK search data into one list of rows. Every optional field may be missing."""
    rows = []
    for kind in ("news", "web"):
        for item in getattr(data, kind) or []:
            if not item.url.startswith(("http://", "https://")):
                continue
            rows.append({
                "kind": kind,
                "url": item.url,
                "title": item.title or item.url,
                "description": item.description or "",
                "source_label": item.source or domain_of(item.url),
                "source_from_api": 1 if item.source else 0,
                "date_text": item.date or None,
                "published_at": parse_date(item.date, now),
                "thumbnail_url": usable_image(item.thumbnail_url),
                "position": item.position,
                "retrieved_at": now.isoformat(timespec="seconds"),
            })
    return rows

Here is a news result that came back with only a title, link, description and relative date:

import json
from spidra import SearchResponseData, SearchResultItem
from normalize import normalize_results

data = SearchResponseData(news=[
    SearchResultItem(title="Example headline", url="https://www.example.com/story", position=1,
                     description="A short description.", date="3 days ago"),
])
print(json.dumps(normalize_results(data, now)[0], indent=2))
{
  "kind": "news",
  "url": "https://www.example.com/story",
  "title": "Example headline",
  "description": "A short description.",
  "source_label": "example.com",
  "source_from_api": 0,
  "date_text": "3 days ago",
  "published_at": "2026-11-17T12:00+00:00",
  "thumbnail_url": null,
  "position": 1,
  "retrieved_at": "2026-11-20T12:00:00+00:00"
}

source_from_api records whether the label came from the search or from the domain. The interface uses it to show derived labels in italics, and the comparison later counts it.

Store every query and its results in SQLite

A topic is a group of queries. Each run stores the query, the sources, the limit, the time range, the result count, and the whole response. Each result row is unique per topic, source type and link:

CREATE TABLE IF NOT EXISTS results (
    id INTEGER PRIMARY KEY, topic_id INTEGER NOT NULL REFERENCES topics(id) ON DELETE CASCADE,
    run_id INTEGER NOT NULL REFERENCES runs(id) ON DELETE CASCADE, query TEXT NOT NULL,
    kind TEXT NOT NULL, url TEXT NOT NULL, title TEXT NOT NULL, description TEXT,
    source_label TEXT NOT NULL, source_from_api INTEGER NOT NULL, date_text TEXT, published_at TEXT,
    thumbnail_url TEXT, position INTEGER, retrieved_at TEXT NOT NULL,
    UNIQUE (topic_id, kind, url));

The UNIQUE constraint does two things. Running a second query that finds the same link updates the row instead of duplicating it. And a link that both news and web return is kept once per source, which is what lets you compare the two later.

def save_run(topic_id, query, sources, limit, time_range, duration_ms, raw, rows):
    with connect() as db:
        cur = db.execute(
            "INSERT INTO runs (topic_id, query, sources, result_limit, time_range, result_count, duration_ms, created_at, raw_json)"
            " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (topic_id, query, ",".join(sources), limit, time_range, len(rows), duration_ms, now(), json.dumps(raw)),
        )
        run_id = cur.lastrowid
        for r in rows:
            db.execute(
                """INSERT INTO results (topic_id, run_id, query, kind, url, title, description, source_label,
                       source_from_api, date_text, published_at, thumbnail_url, position, retrieved_at)
                   VALUES (:topic_id, :run_id, :query, :kind, :url, :title, :description, :source_label,
                       :source_from_api, :date_text, :published_at, :thumbnail_url, :position, :retrieved_at)
                   ON CONFLICT (topic_id, kind, url) DO UPDATE SET
                       run_id = excluded.run_id, query = excluded.query, title = excluded.title,
                       description = excluded.description, source_label = excluded.source_label,
                       source_from_api = excluded.source_from_api, date_text = excluded.date_text,
                       published_at = excluded.published_at, thumbnail_url = excluded.thumbnail_url,
                       position = excluded.position, retrieved_at = excluded.retrieved_at""",
                {**r, "topic_id": topic_id, "run_id": run_id, "query": query},
            )
    return run_id

The stored response is the SDK's result with any field that wasn't returned left out, so the saved copy shows what Spidra sent and nothing else:

def returned_fields(value):
    """Drop fields that were not returned, so the stored response shows only what Spidra sent."""
    if isinstance(value, dict):
        return {k: returned_fields(v) for k, v in value.items() if v is not None}
    if isinstance(value, list):
        return [returned_fields(v) for v in value]
    return value

Run the search from a FastAPI route

The route checks the topic, calls Search, normalizes the results and saves the run. time_range is passed straight through. It favors recent results and isn't a hard cutoff.

@app.post("/api/topics/{topic_id}/search")
def run_search(topic_id: int, body: SearchRequest):
    if not store.topic_exists(topic_id):
        return JSONResponse({"error": "No such topic."}, status_code=404)
    query = body.query.strip()
    try:
        if DEMO:
            result = demo_search(query, body.sources, body.limit)
        else:
            result = client.search(query, sources=body.sources, limit=body.limit, time_range=body.time_range, timeout=120)
    except (SpidraError, httpx.TransportError) as error:
        return error_response(error)
    rows = normalize_results(result.data, datetime.now(timezone.utc))
    run_id = store.save_run(topic_id, query, body.sources, body.limit, body.time_range,
                            result.stats.duration_ms, returned_fields(dataclasses.asdict(result)), rows)
    return {"run_id": run_id, "stored": len(rows), "duration_ms": result.stats.duration_ms}

Errors come back as one JSON shape the page can show. A validation error from Spidra, an out-of-credits account, a rejected key, a rate limit and a lost connection each get their own message and status:

def error_response(error: Exception) -> JSONResponse:
    if isinstance(error, SpidraValidationError):
        status, message = 422, "; ".join(error.errors or [str(error)])
    elif isinstance(error, (SpidraForbiddenError, SpidraPaymentRequiredError)):
        status, message = 402, f"{str(error).rstrip('.')}. Check your balance in the Spidra dashboard."
    elif isinstance(error, SpidraAuthenticationError):
        status, message = 401, "Spidra rejected the API key."
    elif isinstance(error, SpidraRateLimitError):
        status, message = 429, "Too many searches right now. Try again in a moment."
    elif isinstance(error, SpidraTimeoutError):
        status, message = 504, "The search took too long."
    elif isinstance(error, httpx.TransportError):
        status, message = 502, "Could not reach Spidra."
    else:
        status, message = 502, str(error)
    return JSONResponse({"error": message}, status_code=status)

Compare what each source type returned

This is the part that makes the dashboard useful for research. One function returns the coverage per source type for a topic: how many results there are, and how many have a date, a thumbnail and a source name from the search. It also counts the links both sources returned.

def summary(topic_id):
    """Coverage per source type, plus the URLs that both sources returned."""
    with connect() as db:
        kinds = db.execute(
            """SELECT kind, COUNT(*) AS total,
                      SUM(date_text IS NOT NULL) AS with_date,
                      SUM(thumbnail_url IS NOT NULL) AS with_thumbnail,
                      SUM(source_from_api) AS with_api_source
               FROM results WHERE topic_id = ? GROUP BY kind""",
            (topic_id,),
        ).fetchall()
        both = db.execute(
            "SELECT COUNT(*) AS n FROM (SELECT url FROM results WHERE topic_id = ? GROUP BY url HAVING COUNT(DISTINCT kind) > 1)",
            (topic_id,),
        ).fetchone()["n"]
    return {"kinds": {r["kind"]: dict(r) for r in kinds}, "in_both": both}

The page draws these counts as bars under the search box, one column for News and one for Web.

Render the results without trusting the web

Titles, descriptions and links come from other people's pages, so the page never builds HTML from them. Every card is made with createElement and textContent, and links are checked before they're used:

function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  for (const [key, value] of Object.entries(props)) {
    if (key === "class") node.className = value; else if (key === "text") node.textContent = value; else node.setAttribute(key, value);
  }
  for (const child of children) if (child) node.append(child);
  return node;
}
const safeUrl = (u) => /^https?:\/\//i.test(u || "") ? u : "#";
const safeImg = (u) => /^(https?:\/\/|\/demo-thumb\/)/i.test(u || "") ? u : null;

The card then uses those helpers. A missing date reads "No date", and a missing thumbnail gets a plain tile:

const date = r.date_text ? el("span", { class: "date", title: r.published_at ? `Estimated: ${ago(r.published_at)}` : "", text: r.date_text }) : el("span", { class: "date missing", text: "No date" });
const title = el("a", { class: "title", href: safeUrl(r.url), target: "_blank", rel: "noopener noreferrer", text: r.title });
title, el("p", { class: "desc", text: r.description }),

The saved-results box searches titles, descriptions, source labels and the queries that found each result. The pills filter by source type, by results that have a date, and by results that have a thumbnail.

Run the dashboard

cd newsboard
uvicorn app:app

Open http://127.0.0.1:8000, add a topic, type a query and press Run search. Run a few queries across two or three topics, then try the saved-results box and the pills. The raw link beside each run in the history opens the response exactly as it was stored.

What the dashboard doesn't do

  • Update itself. It's query-driven. If you want fresh results every morning, run the search yourself from a scheduler, such as cron.
  • Promise complete coverage. A search returns up to 20 results per source, and the sources differ. Treat it as a way to collect and compare leads, not as an archive of everything published.
  • Guarantee every field. Dates, source names and thumbnails come and go. The dashboard is built to show what's missing instead of hiding it.
  • Page through results. Search can continue past the first results with page tokens (see the Search docs), but this version doesn't.
  • Read the articles. It stores titles, links and short descriptions. For a page's full text, Scrape the link, or ask Search for page content for the top results.
  • Protect itself. There's no login, so keep it on your own machine until you add one.
  • Replace reading the sources. Check a site's terms before you store or republish its content, and read our guide to the legal side of scraping.

Conclusion

You built a news research dashboard: a Search call for news and web, a normalizer that copes with missing fields, a SQLite store that keeps every query and its raw response, and a page that compares what each source type returned. It's about 650 lines because Spidra does the retrieval. One call returns structured results per source, with nothing rewritten, and a failed or empty source doesn't take the others down with it.

Search reaches further than the two sources in this dashboard. The same call can search images, videos, research papers and GitHub issues, favor a country or a recent time range, include or exclude domains, restrict web results to PDFs, and fetch the page content of the top results. Scrape reads any link you've saved, Batch scrape reads up to 50 at once, and Crawl and Map cover whole sites. Parse turns PDFs and Office files into Markdown. Every plan includes every feature, with the plans differing in credits, proxy bandwidth, pages per crawl and monitors, so the dashboard you build on a free account is the one you can grow. Official SDKs cover ten languages, and an MCP server lets AI tools use the same account. For teams doing market research or building news features, that's one API key for finding the pages and reading them. For how Search compares with a scraping API, see Search API vs scraping API.

Create a free account at app.spidra.io (300 credits, no card required), set SPIDRA_API_KEY, and run the dashboard on a topic you follow. You can try a query on the dashboard's Search page before you put it in code.

Frequently asked questions

Pass both sources to Search: client.search("your query", sources=["news", "web"], limit=10). Each source runs on its own and returns up to limit results, so you get a news list and a web list in the same response. A source with no results comes back empty and the other is unaffected.

Share this article

You build the product.
Spidra handles the data work.

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