> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# How do I use X country trends to decide which topics are worth covering?

> Start with a target market, investigate selected trends through actual posts, and hand over an editorial brief with sources, relevance and unresolved checks.

For editorial research in one market, take a country trend snapshot with `twitter.web.fetch_trending`; for Japan, set `country:"Japan"`. Pick the returned topics that are relevant to the brand, then search each topic with `twitter.web.fetch_search_timeline` and read the original posts to confirm what happened and when.

Hand over a brief with the source market, the snapshot time, the original topic name, the supporting posts and the proposed editorial angle, so that a teammate can check every claim in the brief.

## Define the market and content purpose first

Choose the market, the audience and the product question before choosing the country. Record the actual `country` input; do not infer the country from a topic's language or from an account. `twitter.web.fetch_trending` returns a snapshot for one specified country. If you omit `country`, the action returns the United States snapshot, not a global list.

For multiple markets, collect the snapshots close together in time when practical, and keep each snapshot's actual time. List positions are not a heat score that you can compare across countries. An identical name may refer to different events in different markets; verify each market's context before combining the topics.

## Which candidates deserve another read?

Use the table as an editorial guide for common candidate situations:

| Candidate situation                                                  | Initial judgment                               | Next step                                                                          |
| -------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------- |
| Directly relevant to a product use case                              | A possible useful angle                        | Read posts to establish the concrete discussion.                                   |
| A familiar name with unknown current context                         | Background unverified                          | Preserve the exact name and check the event and credible primary sources.          |
| Prominent entertainment or giveaway unrelated to the audience's task | Exclude with a reason                          | Avoid collecting more solely to follow popularity.                                 |
| The same term appears in multiple markets                            | Possibly shared discussion or ambiguous naming | Check each market's context before calling the term a global surge.                |
| Relevant wording but unverifiable material                           | Keep unresolved                                | Do not let AI replace a missing description with an official-sounding explanation. |

Read one page of search results for each selected topic, and check the meaning, the post times and the relevance to the brand. For a strict time window, use the actual returned timestamps. `twitter.web.fetch_search_timeline` has no country filter, so the trend's source country does not show where the authors are.

## What lets a teammate decide whether to publish?

Prepare a short topic card with these items: the market and observation time, the original trend name, the sources actually read, the relevance to the audience, the proposed question or angle, the outstanding checks and a human decision (consider, exclude or unverified). Keep the original names and evidence separate from your editorial summaries.

The local script `prepare_trends.py` creates `trends.csv`, `selected-searches.json` and `coverage.json`. The script organizes saved snapshots and writes an **unexecuted** search plan. The script does not write the topic card, verify news or publish content. Add your editorial reasons in a separate working table. Keep missing values missing; do not manufacture heat, total posts or historical growth that the contract does not provide.

## Use a small scope to decide whether more collection helps

Start with one country snapshot, and approve searches only after choosing topics. If snapshots are already saved, prepare the table locally from the saved snapshots. One country snapshot plus one search page for one topic is two calls. Each additional country, term or page adds a call, priced from each action's current contract.

If the search results are irrelevant, revisit the editorial choice instead of searching every trend automatically. In the brief, state the observation scope and the unresolved evidence. One snapshot is not continuous monitoring and does not prove growth. Steps 1–6 below cover retrieval and local planning.

## 1. Inspect the country input

```bash
curl -sS https://api.beatapi.io/v1/capabilities/inspect \
  -H 'Content-Type: application/json' \
  -d '{"reference":"data:twitter.web.fetch_trending"}'
```

Inspect is free. The input is `country`, with the default `UnitedStates`; the published description also lists values such as `Japan`, `Germany` and `UnitedKingdom`. Do not use another provider's `region: JP`. Omitting `country` selects the default US result, **not a worldwide list**.

## 2. Fetch one country snapshot

Check the current price, then request the Japan snapshot:

```bash
curl -sS https://api.beatapi.io/v1/social-data/call \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"twitter.web.fetch_trending","params":{"country":"Japan"}}' \
  -o x-japan-trends.json
```

Check the execution status. The published list is `data.trends`; each entry includes the topic `name` and a category or `context`. `description` was null in the observed sample. Do not present an AI-written explanation as a returned official description.

## 3. Review names before choosing a topic

The command below reads the saved file only and makes no new request:

```python
import json

with open("x-japan-trends.json", encoding="utf-8") as source:
    result = json.load(source)
if result["status"] != "succeeded":
    raise RuntimeError("Inspect the failed response before using trends")
for position, trend in enumerate(result["data"]["trends"], start=1):
    print(position, trend.get("name", ""), trend.get("context", ""))
```

The printed number is the item's position in the saved response, not a guaranteed official `rank` field. The contract publishes no fixed thirty-item count, no popularity metric, no historical curve and no pagination input, so do not add columns for them.

## 4. Search a returned topic

Inspect the search action before deciding whether to pay for a search:

```bash
curl -sS https://api.beatapi.io/v1/capabilities/inspect \
  -H 'Content-Type: application/json' \
  -d '{"reference":"data:twitter.web.fetch_search_timeline"}'
```

Replace `<returned_trend_name>` with an actual full topic name, properly escaping quotes and other JSON characters:

```bash
curl -sS https://api.beatapi.io/v1/social-data/call \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"twitter.web.fetch_search_timeline","params":{"keyword":"<returned_trend_name>","search_type":"Latest"}}' \
  -o x-trend-posts.json
```

`twitter.web.fetch_search_timeline` has no country input. The returned posts match the topic; the posts are not guaranteed to be written by people in Japan. Review each post's actual text and `lang` for relevance. Choosing a country trend does not filter authors by location.

## 5. Deliver a topic brief

Keep the country input, the retrieval time, the original topic name, the returned context, the supporting posts and your editorial judgment. Verify ambiguous or sensitive events; a trending label is not a confirmed news report.

One country snapshot plus one topic search takes two paid calls. Two countries with one search per country take four. Calculate the cost from each action's current inspected price; another provider's prices and billing rules do not apply.

> Inspect Japan's X trends and price. After approval, fetch one snapshot. Let me choose a topic before approving one search page. Preserve names, time and sources. Do not invent popularity, official ranks or author nationality.

Sources: the free contracts `data:twitter.web.fetch_trending` and `data:twitter.web.fetch_search_timeline`; the guide shows no live trending list. See [keyword search](/guides/x-search-posts) for pagination and CSV export.

## 6. Deliver a country-topic table and a search plan

For a multi-market editorial review, put the saved country snapshots into one table before choosing the topics whose context needs investigation.

1. Create `trend-inputs.json` with the actual `country` sent in each request; do not infer the country from a topic's language.
2. Use one snapshot per country per batch.
3. Select topics by `response_position`, the item's position in one response; `response_position` is not an official rank.

The example below selects the first item of the Japan snapshot without assuming what the item is:

```json
{"snapshots":[{"country":"Japan","file":"x-japan-trends.json","collected_at":"2026-11-16T10:00:00Z"}],"selected":[{"country":"Japan","response_position":1}]}
```

Save the script as `prepare_trends.py` and run `python3 prepare_trends.py trend-inputs.json trend-review`. The script creates `trends.csv`, `selected-searches.json` and `coverage.json`. Each selected name becomes `params.keyword` through JSON encoding, so you never quote names by hand. `prepare_trends.py` makes no request; the script only prepares an unexecuted plan. An empty trend list produces an empty table, and a position that does not exist cannot be selected.

Before executing the plan, inspect the current search price and approve the planned calls. `source_country` records where the topic was discovered; `source_country` is not an author-location filter. After the searches, reuse the search guide's offline exporter and attach the actual posts to the editorial brief. Never present an AI-generated explanation as a missing official description.

```python
import csv
import hashlib
import json
import sys
from datetime import datetime
from pathlib import Path

manifest_file, output = map(Path, sys.argv[1:])
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
snapshots = manifest.get("snapshots")
selected = manifest.get("selected", [])
if not isinstance(snapshots, list) or not snapshots or not isinstance(selected, list):
    raise SystemExit("Expected snapshots and optional selected entries")
rows, by_position, countries, requests = [], {}, set(), set()
evidence = []
for entry in snapshots:
    country = entry.get("country")
    if not isinstance(country, str) or not country.strip() or country != country.strip() or country in countries:
        raise SystemExit("Use one snapshot per distinct country in this batch")
    countries.add(country)
    time = datetime.fromisoformat(entry["collected_at"].replace("Z", "+00:00"))
    if time.utcoffset() is None:
        raise SystemExit("Collection time requires timezone")
    source = manifest_file.parent / entry["file"]
    source_bytes = source.read_bytes()
    digest = hashlib.sha256(source_bytes).hexdigest()
    raw = json.loads(source_bytes)
    if not isinstance(raw, dict) or raw.get("error") is not None or raw.get("status") != "succeeded" or raw.get("action") != "twitter.web.fetch_trending":
        raise SystemExit("Expected a successful direct trend response")
    request_id = raw.get("request_id")
    if not isinstance(request_id, str) or not request_id.strip() or request_id in requests:
        raise SystemExit("Missing or repeated request ID")
    requests.add(request_id)
    data = raw.get("data")
    trends = data.get("trends") if isinstance(data, dict) else None
    if not isinstance(trends, list):
        raise SystemExit("Expected data.trends array")
    evidence.append({"country": country, "collected_at": entry["collected_at"], "request_id": request_id,
                     "source_file": str(source.resolve()), "source_sha256": digest,
                     "saved_file": "raw-" + str(len(evidence) + 1) + ".json", "bytes": source_bytes})
    for position, trend in enumerate(trends, 1):
        if not isinstance(trend, dict):raise SystemExit("Invalid trend object")
        for field in ("context", "description"):
            if trend.get(field) is not None and not isinstance(trend[field], str):raise SystemExit("Unexpected trend text type")
        name = trend.get("name")
        if not isinstance(name, str) or not name.strip():
            raise SystemExit("Missing trend name")
        row = {"country_input": country, "response_position": position, "name": name,
               "context": trend.get("context"), "description": trend.get("description"),
               "collected_at": entry["collected_at"], "source_file": entry["file"], "request_id": request_id, "source_sha256": digest}
        rows.append(row)
        by_position[(country, position)] = row
plan, seen = [], set()
for choice in selected:
    country, position = choice.get("country"), choice.get("response_position")
    if not isinstance(position, int) or isinstance(position, bool):
        raise SystemExit("Choose an integer response position")
    key = (country, position)
    if key not in by_position or key in seen:
        raise SystemExit("Unknown or duplicated selected trend")
    seen.add(key)
    row = by_position[key]
    plan.append({"source_country": country, "source_request_id": row["request_id"], "source_sha256": row["source_sha256"],
                 "action": "twitter.web.fetch_search_timeline", "params": {"keyword": row["name"], "search_type": "Latest"},
                 "executed": False})
output.mkdir(exist_ok=False)
for item in evidence:
    (output / item["saved_file"]).write_bytes(item["bytes"])
(output / "sources.json").write_text(json.dumps([{k: v for k, v in item.items() if k != "bytes"} for item in evidence], ensure_ascii=False, indent=2), encoding="utf-8")
columns = ["country_input", "response_position", "name", "context", "description", "collected_at", "source_file", "request_id", "source_sha256"]
with (output / "trends.csv").open("x", encoding="utf-8-sig", newline="") as handle:
    writer = csv.DictWriter(handle, fieldnames=columns)
    writer.writeheader()
    for row in rows:
        writer.writerow({k: ("'" + v if isinstance(v, str) and v.lstrip().startswith(("=", "+", "-", "@")) else v) for k, v in row.items()})
(output / "selected-searches.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8")
(output / "coverage.json").write_text(json.dumps({"countries": len(countries), "returned_topics": len(rows),
    "planned_search_calls": len(plan), "executed_calls": 0,
    "scope": "response positions, not official ranks; searches do not filter author country"}, indent=2), encoding="utf-8")
```

The output also saves one `raw-N.json` per snapshot and a `sources.json` with each snapshot's original country input, time, request ID and byte hash. Each selected search references the hash of the snapshot the search came from. An empty snapshot still gets a `sources.json` record and a saved raw file, but creates no search-plan item. Keep the original input manifest as well: country and time are recorded request context, not inferred from the response text and not cryptographically verified.