SocialCrawl

Frameworks

SocialCrawl with Flask

Build a Flask app with routes that read a profile, search many platforms and page through posts

One file, app.py, serves three routes under /api, and each answers with the API's JSON unchanged.

Prerequisites

  • Python 3.10 or later.
  • Flask 3.
  • A SocialCrawl API key. Keys start with sc_.

Checking your account…

Set up

Install Flask and requests, then set your key in the shell.

Terminal
pip install flask requests
export SOCIALCRAWL_API_KEY=sc_your_key_here

Keep 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. One requests.Session carries the key on every call.

app.py
import os

import requests
from flask import Flask, request

API = "https://www.socialcrawl.dev"
app = Flask(__name__)
session = requests.Session()
session.headers["x-api-key"] = os.environ["SOCIALCRAWL_API_KEY"]


def socialcrawl(path, params):
    """Answer with the API's JSON and status. Log error.type and error.doc_url when success is false."""
    res = session.get(API + path, params=params, timeout=60)
    body = res.json()
    if not body["success"]:
        app.logger.warning("%s: %s", body["error"]["type"], body["error"].get("doc_url"))
    return body, 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.py
@app.get("/api/profile")
def profile():
    return socialcrawl("/v1/tiktok/profile", {"handle": request.args.get("handle", "charlidamelio")})


@app.get("/api/search")
def search():
    # dry_run=1 prices the search and runs nothing.
    query = request.args.get("query", "oat milk")
    return socialcrawl("/v1/search/everywhere", {"query": query, "format": "compact", "dry_run": 1})


@app.get("/api/posts")
def posts():
    # Send the last answer's pagination.next_cursor back as ?cursor=.
    params = {"handle": request.args.get("handle", "charlidamelio")}
    if request.args.get("cursor"):
        params["cursor"] = request.args["cursor"]
    return 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:5000.

Terminal
flask --app app run

Test it

With the app running, call the three routes. The answers hold data.author.followers, data.estimate and pagination.next_cursor.

Terminal
curl "http://localhost:5000/api/profile?handle=charlidamelio"
curl "http://localhost:5000/api/search?query=oat+milk"
curl "http://localhost:5000/api/posts?handle=charlidamelio&cursor="

Next steps

On this page

Ready to build?

Start getting social data for free and scale as your project grows. No credit card needed.