Lemon8 Content Discovery API Tutorial | SandBase

Connect one Lemon8 main-tab search or known post lookup, validate nested articles and post status, preserve string IDs, and avoid automatic follow-up calls.

Dark cinematic render of a Lemon8 keyword search resolving into a post card and an author profile, feeding an agent core

A keyword, a post ID and a share link are three different starting points for Lemon8 research. The old tutorial treated search as a list of blocks and automatically opened the first post and its author. The current main-tab reference instead shows an object whose articles sit inside data.items[]. Reusing the old parser can silently produce no candidates even when the documented structure contains articles.

This 2026-11-08 repair checks free inspect and public references without making a new business request. It teaches one main-tab search page or one known-post lookup. The original 2026-09-27 UTC experiments remain historical evidence, not a claim that the old workflow was re-run. For other capabilities, see the Lemon8 API hub.

Key takeaway

  • Search uses query, not keyword. This example explicitly selects search_tab: "main" and empty max_cursor for page one.
  • The selected main-tab reference has an object with data.items[].articles[]; do not apply that parser to every tab or keep the old list-of-blocks fallback.
  • A known post uses string item_id with post-detail, whose saved reference has message: "success" and inner data.
  • Share text is a different input. The current resolver is lemon8/app/item-id with share_text; it is a separate request, not an automatic setup step.

The retained cover is conceptual artwork. Its names, content cards, audience counts and analysis labels are illustrative rather than a new result or a verified creator. The pictured multi-step loop is not the current one-request procedure.

Choose the first task

What you haveSelected destinationParameters sent here
A topic or search phraseLemon8 searchquery, search_tab: "main", max_cursor: ""
A known numeric post IDPost detailstring item_id

The search schema also describes user, hashtag and article tabs. Those choices have different purposes; this repair does not establish their response shapes. It omits order_by and filter_type and does not claim to test all sort/filter combinations. The schema defaults main and empty cursor are sent explicitly to make this example’s scope visible.

Use official Lemon8 channels for posting, member actions or account-authorized work. SandBase provides access to the selected public, read-only routes using a SandBase key. A public author object is not authorization to read private content or act as that account.

Historical Lemon8 catalog Historical catalog screenshot retained from the original tutorial. Its entries and labels are navigation context, not a new availability, quota or business-result check.

Reuse the setup you already have

With an existing key, configure SANDBASE_API_KEY in the actual project runtime or secret manager. Keep it out of prompts, screenshots, articles and commits. If authentication fails, inspect that environment before asking an agent to create more credentials or retry repeatedly.

With an already connected agent, specify one task and reuse its credential configuration. For example: “Search the main tab for this phrase once; return the available fields, do not open posts or authors.” If you have a post ID, choose one detail request instead. This gives the agent a clear stopping point even when data is missing.

For a new project, provide SKILL.md and quickstart.md, followed by the chosen task and input. The human quickstart explains the setup. Install requests in the environment that runs the script; do not paste the key into the instructions you give the agent.

One bounded Python request

Python
import os
import re
import requests


def first_request(task, value):
    if task not in ("search", "post"):
        raise ValueError("Choose search or post")
    if not isinstance(value, str) or not value.strip():
        raise ValueError("Supply a nonempty string")
    if task == "post" and not re.fullmatch(r"[0-9]+", value):
        raise ValueError("item_id must be a numeric string, not a URL or None")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set SANDBASE_API_KEY locally")
    path = "search" if task == "search" else "post-detail"
    params = {"query": value, "search_tab": "main", "max_cursor": ""} if task == "search" else {"item_id": value}
    try:
        response = requests.post(
            f"https://api.sandbase.ai/v1/api/lemon8/app/{path}",
            headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
            json=params, timeout=(10, 90), allow_redirects=False,
        )
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"HTTP {response.status_code}; inspect access and budget before retrying")
        body = response.json()
    except ValueError:
        raise RuntimeError("Response was not valid JSON") from None
    except requests.RequestException:
        raise RuntimeError("Network request failed; no automatic retry") from None
    if not isinstance(body, dict) or body.get("status") != "completed":
        raise RuntimeError("SandBase request did not complete")
    outputs = body.get("outputs")
    if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
        raise RuntimeError("Missing outputs[0]")
    payload = outputs[0].get("data")
    if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
        raise RuntimeError("Expected business object and inner data object")
    if task == "search":
        # The trimmed main-tab reference has no message; do not require one.
        if "message" in payload and payload["message"] != "success":
            raise RuntimeError("Unexpected search message; inspect the response")
        groups = payload["data"].get("items")
        if not isinstance(groups, list) or any(
            not isinstance(group, dict) or not isinstance(group.get("articles"), list)
            or any(not isinstance(article, dict) for article in group["articles"])
            for group in groups
        ):
            raise RuntimeError("Expected main-tab data.items groups with articles arrays")
    elif payload.get("message") != "success":
        raise RuntimeError("Post business status was not message success")
    return payload


if __name__ == "__main__":
    result = first_request("search", "OpenAI")
    print("Returned data fields:", sorted(result["data"]))

For a known post, replace the final assignment with result = first_request("post", "7361926875709129222") and keep the field-list print. Do not append it as a second automatic request. This is the current schema’s example ID, not an ID executed in this repair.

The helper returns the unmodified business object. It does not choose a candidate, turn a missing identifier into "None", fetch author profiles, download images, follow links or paginate. An empty items array or empty articles array is accepted; absent or malformed arrays are not silently converted into an empty success.

Search validation deliberately follows the limited main-tab reference. That excerpt does not show a message field, so the helper does not require one. If a response does supply an unexpected message, it stops conservatively rather than treating that response as validated. This is a local guard, not proof of a universal Lemon8 search status convention. A new response shape should be investigated instead of forcing it through the old list parser.

Read groups and articles at their own levels

The public search README labels the following kind of data as a trimmed real response, with names masked. It has no saved full example or exposed run date. The reduced fragment below preserves the shown structure and a few fields, without reproducing identity text or a post URL:

JSON
{
  "data": {
    "has_more": true,
    "items": [
      {
        "articles": [
          {
            "group_id": "7661250232746885645",
            "article_class": "Gallery",
            "language": "en",
            "read_count": 16
          }
        ]
      }
    ]
  }
}

An item is a group containing articles here; it is not itself the post record assumed by the old code. Count the nested articles if you need a count of observed article objects, and keep that separate from the number of groups. Even then, a candidate is not a guarantee of relevance or availability. Inspect its explicit identity fields before deciding whether a detail request is justified.

The visible identifier in this reference is a string group_id. Do not automatically rename every ID field to item_id or infer an author ID from a name. The detail input has its own documented identity requirement. This repair intentionally avoids claiming a freshly tested search-to-detail handoff, because no new business chain was executed.

Pagination is similarly bounded. The schema describes empty max_cursor on the first request and a response-derived cursor for continuation. The short search example shows has_more but not a complete max_cursor. There is no basis here to manufacture a token, increment it numerically or claim a tested stopping rule. The helper makes one first-page request and stops even if has_more is true.

Read post data without confusing fields

The publicly saved post-detail example is dated 2026-10-07. Its response has message success, data and server_time. This trimmed fragment preserves sample counters while omitting identifying text, media and long identifiers:

JSON
{
  "message": "success",
  "data": {
    "article_class": "Gallery",
    "digg_count": 1089,
    "like_count": 1089,
    "favorite_count": 1296,
    "comment_count": 10,
    "share_count": 27,
    "read_count": 82313,
    "view_count": 0
  }
}

These are historical reference values, not current measurements for the schema example ID or a new query. Equal digg_count and like_count in this sample do not prove that the fields are always interchangeable. Favorite count is not a field named collect_count. Read count and view count differ here; zero views must not be silently replaced with read_count to create a more plausible-looking report.

A missing field is unknown, numeric zero is a returned value and false is a boolean state. Preserve all three. Counters do not establish reach quality, conversion or a recent engagement rate. If you compare posts, keep endpoint and retrieval time beside the observed fields rather than treating a single saved sample as a benchmark.

Historical Lemon8 post-detail reference Historical post-detail parameter screenshot. The current procedure passes item_id as a string and checks the saved-reference message/data shape; the image is not a newly executed response.

Keep large IDs intact

Lemon8 IDs can exceed JavaScript’s exact integer range. Pass and store the input as a string. In the saved public capture, numeric item_id/group_id appears as 7613037734357124000, while the article URL contains 7613037734357123615. That is a capture/serialization precision difference, not evidence that a new API request changed a post’s identity.

Converting an already rounded number back to text cannot restore the missing digits. Do not use that numeric capture as an exact-equality assertion against a requested string or copy it into a new request. Keep a verified original string identifier; if you only have a share link, use the documented resolver as a separate decision rather than guessing from an incidental number.

The old post-detail README mentions /lemon8/app/get_item_id. The current free inspect identifies item-id, whose required input is share_text and whose description accepts long or short share links. That correction is contract evidence only: the resolver was not executed here, its output is not guessed, and this tutorial does not add a resolver call automatically.

What the original experiment actually recorded

On 2026-09-27 UTC, the old search run 4bac9e8a-eeec-49ec-ba84-49feff8e1928 was described as a list of blocks with code zero and items carrying item_id/author_id. That observation remains historical and is not the current main-tab contract above.

The old post-detail run was 814a5872-8dae-4fb9-b7be-c3990afd8da6; it recorded data, message and server_time. The old user-profile run a3cf09c5-c08c-4ef7-a898-6a22eeb722ef observed followers_count, following_count, digg_count, comment_count and description, with error_code/message. The author-ID handoff worked in that old run; it is not a blanket promise for every new search group or tab.

All original Python is preserved verbatim in the historical archive, with per-block hashes. It is not current runnable guidance: it accepted an obsolete list shape, selected a first candidate automatically, could stringify None and expanded to every post’s detail and author. The new example replaces that procedure without claiming the historical work was re-run.

Historical Lemon8 user-profile reference Historical user-profile parameter reference. User profiles and the old author-ID handoff were not revalidated in this repair; they are not a mandatory follow-up to search or post detail.

Budget the decision, not just the first call

Search and post-detail currently list $0.001 each, with eligibility for the organization’s shared 100-call daily quota across eligible APIs, resetting at 00:00 UTC. Remaining allowance and balance were not checked. Eligibility cannot promise that your next successful request is free.

The new example performs one selected request. Choosing both independently would list at $0.002 before quota effects. The old discovery function made one search, N post-detail calls and up to N author-profile calls, depending on available author IDs: between 1+N and 1+2N calls, before pagination or retries. This is workload accounting, not a total-price quote for user-profile or other routes not priced in this repair.

HTTP, SandBase status and business shape are separate layers. Redirects, authorization, quota/rate errors, malformed JSON and missing data stop the helper. It does not retry a timeout automatically, because the result may be unknown and another request may add usage. Errors omit raw response bodies, headers and secrets. Offline tests verify those branches, not real-time provider availability.

Questions before you expand

Can I send keyword instead of query? No. The selected search schema requires query. A human description can say “keyword,” but the JSON field name is query.

Does this parser work for Accounts or Hashtags? That is not established. This example fixes main and checks its grouped article structure. Another tab needs its own observed structure and tests.

Can I pass a share URL directly to post-detail? The selected detail input is item_id, not a URL. The current item-id resolver takes share_text as a separate request; the legacy get_item_id name is not the current route.

Will the agent open the best post or profile the author? No. It returns one checked search page or post record. Review identity, missing data and budget first, then use the Lemon8 hub to choose a concrete next task.

Found this useful? Share it