Developer examples

Build with TRMesh social data APIs by example

Move from your first request to pagination, CSV export and concurrent collection with practical templates. Every request goes through TRMesh's /openapi/* proxy path and remains governed by tokens, balance, rate limits, billing and usage logs.

Python / JavaScript / cURL
Bearer-token authentication
Usage logs and billing visibility
sdcenter-first-request.py
import os
import requests

url = "https://api.trmesh.com/openapi/api/v1/instagram/web_app/fetch_user_info_by_username"
headers = {
    "accept": "application/json",
    "Authorization": f"Bearer {os.environ['TRMESH_API_TOKEN']}",
}
params = {"username": "instagram"}

response = requests.get(url, headers=headers, params=params, timeout=30)
print(response.status_code)
print(response.json())
Learning path
01Simple API request
02Pagination and multi-page fetching
03Data extraction and CSV export
04Async and concurrent requests
Before you start

Create a developer token from the authenticated TRMesh workspace.

Confirm that the account has free quota or USD balance before calling paid endpoints.

Use the API docs to verify route status, parameters and the /openapi/* proxy path.

Code examples

The examples use public social-data lookup scenarios. Replace the route, parameters and processing logic with your own workflow.

BeginnerPython
Simple API request
Send your first GET request, fetch a public profile by username and print the status code plus JSON response.
Important notes
  • Set TRMESH_API_TOKEN to a developer token from the workspace.
  • Install dependencies before running locally: pip install requests.
Example codePython
import os
import requests

url = "https://api.trmesh.com/openapi/api/v1/instagram/web_app/fetch_user_info_by_username"
headers = {
    "accept": "application/json",
    "Authorization": f"Bearer {os.environ['TRMESH_API_TOKEN']}",
}
params = {"username": "instagram"}

response = requests.get(url, headers=headers, params=params, timeout=30)
print(response.status_code)
print(response.json())
IntermediateJavaScript
Pagination and multi-page fetching
Loop through cursor or page parameters and merge multiple response pages into one array.
Important notes
  • Pagination fields differ by route, so follow the API docs for the selected endpoint.
  • Always cap the maximum page count for worker jobs.
Example codeJavaScript
const token = process.env.TRMESH_API_TOKEN;
const collected = [];
let cursor = "0";

for (let page = 0; page < 3; page += 1) {
  const url = new URL("https://api.trmesh.com/openapi/api/v1/tiktok/web/fetch_user_post_videos");
  url.searchParams.set("secUid", "example-sec-uid");
  url.searchParams.set("cursor", cursor);
  url.searchParams.set("count", "20");

  const response = await fetch(url, {
    headers: { Authorization: `Bearer ${token}`, accept: "application/json" },
  });

  if (!response.ok) throw new Error(`TRMesh request failed: ${response.status}`);
  const payload = await response.json();
  collected.push(...(payload.data?.items ?? []));
  cursor = payload.data?.cursor ?? "";
  if (!cursor) break;
}

console.log(collected.length);
IntermediatePython
Data extraction and CSV export
Extract the fields your business needs and write them into a CSV file for spreadsheets, CRM or BI tools.
Important notes
  • Persist only the fields needed by your workflow.
  • Normalize empty values before importing into downstream systems.
Example codePython
import csv
import os
import requests

response = requests.get(
    "https://api.trmesh.com/openapi/api/v1/instagram/web_app/fetch_user_info_by_username",
    headers={"Authorization": f"Bearer {os.environ['TRMESH_API_TOKEN']}"},
    params={"username": "instagram"},
    timeout=30,
)
response.raise_for_status()
profile = response.json().get("data", {})

with open("sdcenter_profiles.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["username", "nickname", "followers"])
    writer.writeheader()
    writer.writerow({
        "username": profile.get("username", ""),
        "nickname": profile.get("nickname", ""),
        "followers": profile.get("follower_count", 0),
    })
AdvancedJavaScript
Async and concurrent requests
Query multiple accounts with a small concurrency cap so workers stay below the account's RPS level.
Important notes
  • Keep concurrency below the workspace RPS configuration.
  • Use retry and backoff for 429, 500 and 502 responses.
Example codeJavaScript
const token = process.env.TRMESH_API_TOKEN;
const usernames = ["instagram", "youtube", "tiktok"];
const concurrency = 2;

async function fetchProfile(username) {
  const url = new URL("https://api.trmesh.com/openapi/api/v1/instagram/web_app/fetch_user_info_by_username");
  url.searchParams.set("username", username);
  const response = await fetch(url, {
    headers: { Authorization: `Bearer ${token}`, accept: "application/json" },
  });
  if (response.status === 429) throw new Error("rate limited");
  if (!response.ok) throw new Error(`request failed: ${response.status}`);
  return response.json();
}

for (let index = 0; index < usernames.length; index += concurrency) {
  const batch = usernames.slice(index, index + concurrency);
  const results = await Promise.all(batch.map(fetchProfile));
  console.log(results.map((item) => item.data?.username));
}

HTTP status codes

Start troubleshooting with the status code, then check usage logs, wallet records and error details in the workspace.

400

Bad Request

The request format is invalid, required parameters are missing, or values do not match the selected route.

401

Unauthorized

The token is missing, invalid, expired or cannot be matched to an active user.

402

Payment Required

The account does not have enough free quota or USD balance for this paid request.

403

Forbidden

The account, email verification state, token permission or route access does not allow the request.

404

Not Found

The route is not registered, not online, or the requested data does not exist.

429

Too Many Requests

The request rate exceeded the account's RPS level. Lower concurrency or upgrade the level before retrying.

500 / 502

Server / Data Service Error

The platform or data-service provider is temporarily unavailable. Retry or degrade based on business tolerance.

Frequently asked questions

Common development questions around tokens, balance, rate limits, payments and data responsibility.

What should I do when a request times out?

Reduce the request scope, lower page size and add retry logic. Worker jobs should persist cursor and progress so they do not restart from the beginning.

Why do I get a 402 response?

The selected route is paid and the account does not have enough free quota or USD balance to cover this request.

Why do I get a 403 response?

Common causes include an unverified account, frozen account, insufficient token permission or route access not enabled for the user.

Can I test the API for free?

New users can use trial quota for validation. Whether a specific API accepts trial quota is reflected in the API details and account request result.

How many tokens should I create?

Follow the workspace token limits. For production, split tokens by application or environment so access can be audited and deleted cleanly.

Who is responsible for downstream data use?

TRMesh provides access, orchestration and governance. Users remain responsible for how retrieved data is stored, exported and processed downstream.

Ready to make real requests?

Create an account, generate a token and choose an online route in the API docs. This page explains integration patterns; runtime access still follows workspace permissions, pricing and route status.