Frameworks
SocialCrawl with FastAPI
Build an async FastAPI service that reads a profile, searches many platforms and pages through posts
One file, main.py, serves three routes under /api, and each answers with the API's JSON unchanged.
Prerequisites
- Python 3.10 or later.
- FastAPI and uvicorn.
- A SocialCrawl API key. Keys start with
sc_.
Checking your account…
Set up
Install FastAPI, uvicorn and httpx, then set your key in the shell.
pip install fastapi uvicorn httpx
export SOCIALCRAWL_API_KEY=sc_your_key_hereKeep the key on the server, out of your code and out of the browser.
Create the client
This code sends your key in the x-api-key header. The lifespan opens one httpx.AsyncClient and closes it when the app stops.
import logging
import os
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
from fastapi.responses import JSONResponse
API = "https://www.socialcrawl.dev"
logger = logging.getLogger("socialcrawl")
@asynccontextmanager
async def lifespan(app: FastAPI):
# One client for the app's whole life, with your key on every request.
async with httpx.AsyncClient(
base_url=API, headers={"x-api-key": os.environ["SOCIALCRAWL_API_KEY"]}, timeout=60
) as client:
app.state.socialcrawl = client
yield
app = FastAPI(lifespan=lifespan)
async def socialcrawl(path: str, params: dict) -> JSONResponse:
"""Answer with the API's JSON and status. Log error.type and error.doc_url when success is false."""
res = await app.state.socialcrawl.get(path, params=params)
body = res.json()
if not body["success"]:
logger.warning("%s: %s", body["error"]["type"], body["error"].get("doc_url"))
return JSONResponse(body, status_code=res.status_code)Branch on success, then on error.type, never on the message text.
Create the routes
Each of the three routes under /api makes one call and answers with what comes back.
@app.get("/api/profile")
async def profile(handle: str = "charlidamelio"):
return await socialcrawl("/v1/tiktok/profile", {"handle": handle})
@app.get("/api/search")
async def search(query: str = "oat milk"):
# dry_run=1 prices the search and runs nothing.
return await socialcrawl(
"/v1/search/everywhere", {"query": query, "format": "compact", "dry_run": 1}
)
@app.get("/api/posts")
async def posts(handle: str = "charlidamelio", cursor: str = ""):
# Send the last answer's pagination.next_cursor back as ?cursor=.
params = {"handle": handle}
if cursor:
params["cursor"] = cursor
return await socialcrawl("/v1/tiktok/profile/videos", params)With dry_run=1 the search is free. Drop it to run the search for 20 credits. A page of posts costs 1 credit. Send pagination.next_cursor back as cursor, and stop when pagination.has_more is false.
Run it
Start the app. It listens on http://localhost:8000.
uvicorn main:app --port 8000Test it
With the app running, call the three routes. The answers hold data.author.followers, data.estimate and pagination.next_cursor.
curl "http://localhost:8000/api/profile?handle=charlidamelio"
curl "http://localhost:8000/api/search?query=oat+milk"
curl "http://localhost:8000/api/posts?handle=charlidamelio&cursor="