Languages
SocialCrawl in Rust
Read a profile, search many platforms and page through posts from Rust with reqwest
Each step adds to one file, src/main.rs, and cargo run --quiet runs all three at the end.
Prerequisites
- Rust stable (1.80 or later) and Cargo.
- A SocialCrawl API key. Keys start with
sc_.
Checking your account…
Set your API key
In an empty folder, create a crate and add two dependencies. Then set your key in the shell.
cargo init --name quickstart
cargo add reqwest --features blocking,json
cargo add serde_json
export SOCIALCRAWL_API_KEY=sc_your_key_hereKeep the key on the server, out of your code and out of the browser.
Write a small client
Save this as src/main.rs. call sends your key in the x-api-key header and returns an error when success is false. main runs the three steps below in order.
use reqwest::blocking::Client;
use serde_json::{json, Value};
use std::{env, error::Error, process, time::Duration};
const API: &str = "https://www.socialcrawl.dev";
// Send one request. Return an error carrying error.type and error.doc_url when success is false.
fn call(client: &Client, path: &str, query: &[(&str, &str)]) -> Result<Value, Box<dyn Error>> {
let key = env::var("SOCIALCRAWL_API_KEY").unwrap_or_default();
let url = reqwest::Url::parse_with_params(&format!("{API}{path}"), query)?;
let body: Value = client
.get(url)
.header("x-api-key", key)
.send()?
.json()?;
if body["success"] != true {
let error = &body["error"];
return Err(format!(
"{}: {} ({})",
error["type"].as_str().unwrap_or("UNKNOWN"),
error["message"].as_str().unwrap_or(""),
error["doc_url"].as_str().unwrap_or(""),
)
.into());
}
Ok(body)
}
fn main() {
if let Err(error) = run() {
eprintln!("{error}");
process::exit(1);
}
}
fn run() -> Result<(), Box<dyn Error>> {
let client = Client::builder().timeout(Duration::from_secs(60)).build()?;
get_profile(&client)?;
search(&client)?;
get_posts(&client)?;
Ok(())
}Get a profile
Add this to src/main.rs.
fn get_profile(client: &Client) -> Result<(), Box<dyn Error>> {
let profile = call(client, "/v1/tiktok/profile", &[("handle", "charlidamelio")])?;
println!(
"followers: {} (credits_used {})",
profile["data"]["author"]["followers"], profile["credits_used"]
);
Ok(())
}It prints the follower count from data.author.followers and the credits_used of the call.
Every answer carries success. Branch on it, then on error.type, never on the message text.
Search across platforms
Add this to src/main.rs. With dry_run=1 the search runs nothing and is free. data.estimate holds what the real search would cost and how many seconds it would take.
fn search(client: &Client) -> Result<(), Box<dyn Error>> {
let query = [("query", "oat milk"), ("format", "compact"), ("dry_run", "1")];
let quote = call(client, "/v1/search/everywhere", &query)?;
let estimate = "e["data"]["estimate"];
println!(
"estimate: {}",
json!({ "credits": estimate["credits"], "seconds": estimate["seconds"] })
);
Ok(())
}Drop dry_run to run the search for 20 credits.
Get posts and the next page
Add this to src/main.rs. Each answer holds one page of posts in data.items. Send pagination.next_cursor back as cursor, and stop when pagination.has_more is false.
fn get_posts(client: &Client) -> Result<(), Box<dyn Error>> {
let mut cursor = String::new();
for page in 1..=2 {
let mut query = vec![("handle", "charlidamelio")];
if !cursor.is_empty() {
query.push(("cursor", cursor.as_str()));
}
let posts = call(client, "/v1/tiktok/profile/videos", &query)?;
let pagination = &posts["pagination"];
let next = pagination["next_cursor"].as_str();
let items = posts["data"]["items"].as_array().map_or(0, Vec::len);
println!(
"page {page}: {items} posts (credits_used {}), next_cursor {}",
posts["credits_used"],
next.unwrap_or("null")
);
if pagination["has_more"] != true {
break;
}
cursor = next.unwrap_or_default().to_string();
}
Ok(())
}A page of posts costs 1 credit. Run cargo run --quiet to see all three steps.
