탐색으로 건너뛰기

How do I collect Xiaohongshu campaign results and explain them to a client?

To review a batch of live sponsored Xiaohongshu posts for a client, fix the agreed note roster, fetch the same notes at agreed times with data:xiaohongshu.app_v2.get_image_note_detail or data:xiaohongshu.app_v2.get_video_note_detail, and deliver a change table traceable to its sources. The table shows which posts are still accumulating engagement, which need another check and what remains unsupported. Newly discovered popular posts cannot replace the actual campaign roster.

The workflow collects public likes, saves, comments and shares, keeps each observation and compares two rounds. Reads and impressions have separate definitions; the final PGY section exports only the documented PGY subset. Sales, acquisition, attributed follows and a complete campaign closure still require the relevant order and dashboard evidence.

Agree which client question you are answering

For a few posts, manual recording can be enough. Use the scripts on this page when repeated observations across many posts need preserved sources. Agree the roster, observation windows, metrics and budget before collecting.

Client questionHow to use this deliverableWhat else is needed
What engagement does each campaign post have now?One row per note with public counts and actual retrieval timeList missing records separately; missing is not zero.
Has anything increased since the last observation?Compare the same note’s before, after and net changeBoth rounds need the metric; retain negative changes.
Which creators or content deserve further research?Check coverage and post age, then examine content and discussionEngagement does not establish campaign-attributed sales or quality.
What impressions, reads, follows or sales did this produce?Check definitions and attribution windows in an authorized dashboardPublic counts cannot supply absent impression or conversion evidence.

Read coverage gaps before increases

The rows below are fictional interpretation examples, not collected findings:

What the table showsWhat you can reportNext check
The same post’s saves move from 100 to 150 at known timesA net increase of 50 saves in the observation intervalRead the content and discussion; 50 more saves are not 50 new buyers.
A post appears only in follow-upData was retrieved in this round, but no baseline existsInspect the baseline journal instead of inserting zero.
A roster post is absent in both roundsBoth observations are missing for an agreed postCheck missed collection, request failure or content status before claiming deletion.
Comments decrease from 120 to 115The observed counter decreased by fiveCheck times, sources and definitions; do not rewrite the decrease to zero or infer a backlash.

When comparing posts, count from each post’s publication date and align snapshots, such as day 1 and day 7. If one post is seven days old and another is thirty days old, put the thirty-day post in the longer-window comparison. Show both observation times beside every change in the report.

How should I run a collection round?

  1. Fix the roster: keep each note ID, image/video type, campaign batch and original link. Do not pay for search to rediscover known IDs. The comparison script’s roster.json contains only the agreed ID strings; keep creator and batch context in the campaign working table.
  2. Agree the observation ages, such as days 1, 7 and 30 after publication. Record actual times separately from planned times. The page provides no scheduled collector, and export time is not collection time.
  3. Save the original responses from the matching image or video detail action. When a note’s type is unknown, confirm the type instead of trying both paid actions. Keep a separate file for each post and round.
  4. Reconcile the roster first. Put verified successes in the round’s input manifest, and record failures or missed requests in a journal. Invalid inputs stop the export instead of creating zeros. Approve a retry budget, and retry only the failed targets.
  5. Compare two observations of the same roster. Confirm that the baseline is the earlier observation before running the local comparison. Explain gaps first, then comparable changes, then questions for the creator or client.

Hand over the snapshot CSVs, the change CSV and a short explanation: planned notes, actual coverage, missing targets and reasons, comparable changes and unresolved evidence. Keep raw responses and manifests privately for verification. Content judgments and recommendations are human additions to a working copy; the scripts do not score creators.

Estimate cost and reuse observations already saved

Each round costs (image notes × current image-detail price) + (video notes × current video-detail price); add up the approved rounds. Inspect each price first. PGY fields, comments and model analysis are billed separately. Failed or business-error queries can still incur charges; another service’s free-error policy does not apply.

Editing tables and re-comparing saved files need no new collection. Query again only when you need a new observation. The Python scripts below process local files; the scripts never purchase data or upload client reports.

Complete the public-engagement workflow in steps 1–6 first. Use the final PGY section only when impressions or reads are actually required, and keep PGY actions, fields and costs separate.

1. Inspect the appropriate detail contract

Image notes use data:xiaohongshu.app_v2.get_image_note_detail; video notes use data:xiaohongshu.app_v2.get_video_note_detail. Inspect only the actions you need, and confirm the current price and business-error notices.

curl -sS https://api.beatapi.io/v1/capabilities/inspect \
-H 'Content-Type: application/json' \
-d '{"reference":"data:xiaohongshu.app_v2.get_image_note_detail"}'

Do not query both actions automatically to discover a note’s type; verify the note’s source first. Invalid IDs or parsing failures can return normal, billed business-error responses.

2. Retrieve and save a note

curl -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"action":"xiaohongshu.app_v2.get_image_note_detail","params":{"note_id":"<note_id>"}}' \
-o note-1.json

For a verified video ID, use the video action instead. Keep a distinct file for each note and collection time instead of overwriting earlier responses. Record the collection time of each query; export time is not retrieval time.

3. Prepare a local target manifest

Create targets.json and replace the placeholders with actual IDs, response filenames and collection timestamps. targets.json is a manifest for the local exporter, not an API request schema.

[
{"note_id":"<note_id>","file":"note-1.json","collected_at":"<actual_collection_time>"}
]

Image notes are at data.data[].note_list[] and video notes at data.data[]. A response can contain other notes, so match the target ID instead of taking the first object.

4. Export locally

Run the exporter below in the directory that holds the manifest and responses. Failed queries, unknown actions or unmatched targets stop processing instead of producing zero-filled rows. Missing metrics stay blank, and an actual zero stays zero. The exporter checks all rows before replacing the CSV.

import csv
import json
from datetime import datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
def count(value):
if value is None:
return None
try:
if isinstance(value, bool):
raise ValueError()
number = Decimal(str(value))
if not number.is_finite() or number < 0 or number != number.to_integral_value():
raise ValueError()
return int(number)
except (ValueError, InvalidOperation):
raise SystemExit("Expected a nonnegative integer count")
targets = json.loads(Path("targets.json").read_text(encoding="utf-8"))
rows = []
seen = set()
if not isinstance(targets, list):
raise SystemExit("Expected a target list")
for target in targets:
key = target.get("note_id")
if not isinstance(key, str) or not key or key in seen:
raise SystemExit("Missing or duplicate target ID")
seen.add(key)
try:
stamp = datetime.fromisoformat(target["collected_at"].replace("Z", "+00:00"))
if stamp.utcoffset() is None:
raise ValueError()
except (KeyError, ValueError, TypeError, AttributeError):
raise SystemExit("Collection time must include date, time and timezone")
payload = json.loads(Path(target["file"]).read_text(encoding="utf-8"))
if payload.get("status") != "succeeded":
raise SystemExit(f"Failed query: {target['file']}")
upstream = payload.get("data", {})
if upstream.get("success") is False or ("code" in upstream and upstream["code"] != 0):
raise SystemExit(f"Upstream business error: {target['file']}")
if not payload.get("request_id"):
raise SystemExit("Missing request ID")
action = payload["action"]
if action == "xiaohongshu.app_v2.get_image_note_detail":
notes = [note for wrapper in payload["data"]["data"] for note in wrapper.get("note_list", [])]
elif action == "xiaohongshu.app_v2.get_video_note_detail":
notes = payload["data"]["data"]
else:
raise SystemExit(f"Unexpected action: {action}")
matches = [note for note in notes if note.get("id") == target["note_id"]]
if len(matches) != 1:
raise SystemExit(f"Target must match exactly once: {target['note_id']}")
note = matches[0]
rows.append({
"note_id": target["note_id"],
"title": note.get("title"),
"likes": count(note.get("liked_count")),
"saves": count(note.get("collected_count")),
"comments": count(note.get("comments_count")),
"shares": count(note.get("shared_count")),
"views": count(note.get("view_count")),
"collected_at": target["collected_at"],
"request_id": payload["request_id"],
"source_file": target["file"],
})
if not rows:
raise SystemExit("No targets; keep the previous CSV unchanged.")
def safe_cell(value):
if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")):
return "'" + value
return value
temporary = Path("note-metrics.csv.tmp")
with temporary.open("w", encoding="utf-8-sig", newline="") as output:
writer = csv.DictWriter(output, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows({key: safe_cell(value) for key, value in row.items()} for row in rows)
temporary.replace("note-metrics.csv")

5. Compare observations without inventing attribution

Keep each run’s CSV and original JSON, and join snapshots by note_id. A difference in totals is an observed net change; the difference does not prove that the campaign caused the change or that counts were never revised. A missing view_count is not zero, and an absent impression field cannot support impression-cost calculations.

In spreadsheet software, import IDs as text so long identifiers are not rewritten. The code handles formula prefixes, multiline text and quotes, but does not normalize every optional field or metric time definition.

Turn campaign follow-up into an auditable change table

Keep the agreed note roster, note types and observation schedule fixed; do not replace the sample with a fresh search each round. Save each original response. Retry only the failed notes, not the whole successful batch. A deleted, unavailable or missed note is missing coverage, not zero engagement.

Copy the two exported snapshots to baseline.csv and followup.csv, then run the code below in the same directory. The deliverable, note-metric-changes.csv, contains both observation times, the source files and each metric’s before, after and net change. IDs present in both snapshots are matched; one-sided IDs stay as new_only or baseline_only. A metric missing on either side leaves the change blank. Negative changes are kept as counter reductions.

Before comparing, create a separate roster.json with the agreed note ID strings, for example ["<note_id_1>","<note_id_2>"]. Do not derive roster.json from either successful snapshot; otherwise notes absent from both snapshots disappear. The output uses missing_both when neither round contains a roster ID, and an ID outside the roster stops validation.

The comparison completes a fixed-roster review of saved responses, not automated batch collection. The first exporter still stops on failed responses. Keep a separate failures.json journal with note ID, round, request time, error and raw filename, and put only verified successful responses into the round’s targets.json before exporting. Missing coverage alone cannot distinguish deletion, request failure and a missed request; consult failures.json. If a whole round has no successful results, resolve the failure first; do not pass an old CSV off as a new snapshot.

import csv
import json
from decimal import Decimal, InvalidOperation
from pathlib import Path
metrics = ("likes", "saves", "comments", "shares", "views")
def load_snapshot(filename):
with Path(filename).open(encoding="utf-8-sig", newline="") as source:
rows = list(csv.DictReader(source))
result = {}
for row in rows:
key = row["note_id"]
if not key or key in result:
raise SystemExit(f"Missing or duplicate note ID in {filename}")
if not row["collected_at"]:
raise SystemExit(f"Missing collection time in {filename}")
result[key] = row
if not result:
raise SystemExit(f"Empty snapshot: {filename}")
return result
roster = json.loads(Path("roster.json").read_text(encoding="utf-8"))
if not isinstance(roster, list) or not roster or any(not isinstance(v, str) or not v for v in roster):
raise SystemExit("Expected a nonempty roster of note ID strings")
if len(roster) != len(set(roster)):
raise SystemExit("Duplicate ID in roster")
before = load_snapshot("baseline.csv")
after = load_snapshot("followup.csv")
if (before.keys() | after.keys()) - set(roster):
raise SystemExit("Snapshot contains IDs outside the agreed roster")
rows = []
for note_id in roster:
old, new = before.get(note_id), after.get(note_id)
row = {
"note_id": note_id,
"coverage": "matched" if old and new else ("new_only" if new else ("baseline_only" if old else "missing_both")),
"before_collected_at": old["collected_at"] if old else "",
"after_collected_at": new["collected_at"] if new else "",
"before_source_file": old["source_file"] if old else "",
"after_source_file": new["source_file"] if new else "",
}
for metric in metrics:
a, b = old.get(metric, "") if old else "", new.get(metric, "") if new else ""
row[metric + "_before"], row[metric + "_after"] = a, b
numbers = []
for value in (a, b):
if value == "":
numbers.append(None)
continue
try:
number = Decimal(value)
if not number.is_finite() or number < 0 or number != number.to_integral_value():
raise InvalidOperation
numbers.append(number)
except InvalidOperation:
raise SystemExit(f"Non-numeric {metric} for {note_id}")
delta = numbers[1] - numbers[0] if all(v is not None for v in numbers) else ""
row[metric + "_delta"] = delta
rows.append(row)
def safe_cell(value):
if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")):
return "'" + value
return value
temporary = Path("note-metric-changes.csv.tmp")
with temporary.open("w", encoding="utf-8-sig", newline="") as output:
writer = csv.DictWriter(output, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows({key: safe_cell(value) for key, value in row.items()} for row in rows)
temporary.replace("note-metric-changes.csv")

Review the non-matched rows for coverage gaps first, then use likes_delta, saves_delta and comments_delta to compare public engagement within the roster. Notes can have different collection times, so the deltas are observed changes, not a platform-aligned attribution window. The script compares file roles and does not infer time order; verify that the baseline is the earlier snapshot.

A concrete AI task

Use my fixed note roster and verified types to inspect the appropriate detail actions, save this round’s raw responses and actual retrieval timestamps, then join the baseline and follow-up by note ID. Export before/after values, net changes and missing coverage. Do not replace the sample with new search results, fill missing metrics with zero, or invent impressions or attribution. Report estimated call count and current prices before obtaining authorization for collection. Comparing saved files runs locally.

6. Costs and verification

Querying N notes once takes N detail calls. Re-exporting saved responses adds no platform calls. A refresh is another query; price each action from the current Inspect result and check each action’s billing boundaries separately.

Sources: offline fixtures that verify both output paths, exact target matching, missing versus zero values, formula handling and preservation of an existing CSV on failure; no paid collection or campaign-effect test was run. See campaign-report gaps for unverified fields.

Build the documented PGY exposure/read subset of a campaign report

For a campaign roster that needs exposure and reading counts, the documented PGY detail description supplies concrete paths. BeatAPI’s renderer preserves the nested envelope: data.data.noteId, impNum (exposures), readNum (reads), likeNum, favNum and cmtNum. Do not import a competitor’s normalized metrics, attributed follows, shares, brand or component-click fields: the PGY description does not establish those outputs. Sources: the PGY documentation, the gateway renderer and synthetic test fixtures; no paid PGY test was run.

First freeze the note roster for one observation round. Free Inspect checked on 2026-11-16 quotes $0.06 per PGY detail request. Thirty notes require 30 requests, $1.80 at that checked price, excluding discovery and rechecks. Refresh prices before running the requests. Request only the notes in scope, save failures as well as successes, and never repeat a null result automatically.

{"action":"xiaohongshu.pgy.get_note_detail","params":{"note_id":"0123456789abcdef01234567"}}

The note ID in the request above is illustrative, not a query to run. For each actual full response, record a matching manifest entry. Use a new directory for each round; the converter makes no calls.

[{"note_id":"0123456789abcdef01234567","action":"xiaohongshu.pgy.get_note_detail","params":{"note_id":"0123456789abcdef01234567"},"http_status":200,"collected_at":"2026-11-16T10:00:00Z","response_file":"pgy-note.json"}]

Save the following as pgy_report.py. pgy_report.py requires verified 24-character note IDs, validates the returned note identity and an explicit inner business success, and keeps unsuccessful roster rows instead of silently dropping the rows. Counts accept nonnegative integers or plain digit strings; missing values stay blank, and unsupported formatted values stop the conversion for inspection.

import csv,datetime,hashlib,json,pathlib,re,sys
manifest,target=map(pathlib.Path,sys.argv[1:3])
entries=json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(entries,list) or not entries:raise ValueError("Nonempty roster manifest required")
fields={"impressions":"impNum","reads":"readNum","likes":"likeNum","saves":"favNum","comments":"cmtNum"}
rows=[];seen=set();request_ids=set()
def count(value):
if value is None:return ""
if type(value) is int and value>=0:return value
if isinstance(value,str) and re.fullmatch(r"[0-9]+",value):return int(value)
raise ValueError("Count must be a nonnegative integer or digit string")
def cell(value):
text=str(value)
return "'"+text if text.lstrip().startswith(("=","+","-","@")) or text.startswith(("\t","\r","\n")) else text
for entry in entries:
note=entry["note_id"]
if not isinstance(note,str) or not re.fullmatch(r"[0-9a-fA-F]{24}",note) or note in seen:
raise ValueError("Use distinct verified 24-character note IDs in this round")
seen.add(note)
if entry.get("action")!="xiaohongshu.pgy.get_note_detail" or entry.get("params")!={"note_id":note}:
raise ValueError("Manifest must bind the actual action and note_id params")
http_status=entry.get("http_status")
if type(http_status) is not int or not 100<=http_status<=599:raise ValueError("Record actual HTTP status")
stamp=entry["collected_at"]
if datetime.datetime.fromisoformat(stamp.replace("Z","+00:00")).tzinfo is None:raise ValueError("Timestamp needs timezone")
path=pathlib.Path(entry["response_file"])
if not path.is_absolute():path=manifest.parent/path
raw=path.read_bytes();response=json.loads(raw)
error=response.get("error")
if error is not None:
if not isinstance(error,dict) or http_status<400:raise ValueError("Invalid HTTP error envelope")
if not isinstance(error.get("code"),str) or not error["code"].strip():raise ValueError("Missing error code")
request_id=error.get("request_id")
else:
if http_status!=200 or response.get("action")!="xiaohongshu.pgy.get_note_detail":raise ValueError("Unexpected response action or HTTP status")
request_id=response.get("request_id")
if not isinstance(request_id,str) or not request_id.strip() or request_id in request_ids:raise ValueError("Distinct request IDs required")
request_ids.add(request_id)
row={"note_id":note,"collected_at":stamp,"request_id":request_id,"source_file":str(path),
"source_sha256":hashlib.sha256(raw).hexdigest(),"state":"gateway_failed","http_status":http_status,"error_code":error["code"] if error is not None else "",
**{key:"" for key in fields},"read_to_impression_ratio":"","ratio_state":"unavailable"}
if error is None and response.get("status")=="succeeded":
envelope=response.get("data")
if not isinstance(envelope,dict):raise ValueError("Missing PGY envelope")
if envelope.get("success") is False:row["state"]="pgy_business_failed"
elif envelope.get("success") is not True:raise ValueError("PGY success must be explicit boolean")
elif envelope.get("data") is None:row["state"]="no_payload"
else:
data=envelope["data"]
if not isinstance(data,dict) or data.get("noteId")!=note:raise ValueError("Response note identity mismatch")
for label,key in fields.items():row[label]=count(data.get(key))
row["state"]="available" if all(row[key]!="" for key in fields) else "partial_metrics"
imp,reads=row["impressions"],row["reads"]
if imp=="" or reads=="":row["ratio_state"]="missing_input"
elif imp==0:row["ratio_state"]="zero_denominator"
else:
row["read_to_impression_ratio"]=reads/imp
row["ratio_state"]="review_gt_one" if reads>imp else "computed"
elif error is None:raise ValueError("Unexpected gateway status")
rows.append(row)
summary={"roster_notes":len(rows),"state_counts":{},"scope":"One saved observation round; no attributed follows or component clicks"}
for row in rows:summary["state_counts"][row["state"]]=summary["state_counts"].get(row["state"],0)+1
target.mkdir()
with (target/"pgy-note-report.csv").open("x",encoding="utf-8-sig",newline="") as output:
writer=csv.DictWriter(output,fieldnames=list(rows[0]));writer.writeheader()
writer.writerows({key:cell(value) for key,value in row.items()} for row in rows)
(target/"coverage.json").write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding="utf-8")
print(str(target/"pgy-note-report.csv"))

Run python3 pgy_report.py pgy-manifest.json pgy-round-1. Review coverage.json before sorting the CSV. Rows distinguish gateway failure, inner business failure, null data, partial metrics and available metrics. The raw responses remain the evidence for error details and original field representation; keep the raw responses with the manifest.

read_to_impression_ratio is the script’s arithmetic reads/exposures, not a platform-provided conversion rate or unique-reader metric. Missing input yields a blank; zero exposures yield a blank with zero_denominator; reads greater than exposures keep the calculated result with the review_gt_one flag instead of clamping. Check collection times and metric definitions before comparing notes. Do not report the PGY subset as a complete attribution report. The output directory must not exist; after an interrupted write, inspect the partial directory before using a new name.

Record the actual HTTP status as well as the action and params in the manifest. HTTP errors carry error.code and error.request_id, not a synthetic top-level failed result. Keep the response body even when curl exits nonzero. Record a network failure with no JSON response in a separate collection log; the converter cannot invent an HTTP result for such a failure.

To collect an authorized note, save the real request JSON as pgy-request.json, then run the command below once with fresh output names. Copy the actual status from pgy-http-status.txt into the note’s manifest entry, and never overwrite an existing round. The command is an optional paid collection step, not part of local conversion.

curl --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
--data-binary @pgy-request.json \
-o pgy-note.json -w '%{http_code}\n' > pgy-http-status.txt