> Documentation index: https://www.socialcrawl.dev/llms.txt > Every page is also available as Markdown by adding .md. # FastAPI (/docs/quickstart/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_`. Get a free API key at https://www.socialcrawl.dev/dashboard/api. New accounts start with 100 welcome credits and no card is needed. ## Set up Install FastAPI, uvicorn and `httpx`, then set your key in the shell. ```bash title="Terminal" pip install fastapi uvicorn httpx 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. The lifespan opens one `httpx.AsyncClient` and closes it when the app stops. ```python title="main.py" 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. ```python title="main.py" @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`. ```bash title="Terminal" uvicorn main:app --port 8000 ``` ## Test it With the app running, call the three routes. The answers hold `data.author.followers`, `data.estimate` and `pagination.next_cursor`. ```bash title="Terminal" 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=" ``` ## Next steps - [Price a watch for free](/docs/engines/monitors.md): POST /v1/monitors?dry_run=1 quotes a scheduled watch of an account and creates nothing. - [Common jobs](/docs/common-jobs.md): The first call for each job, from profiles to comments and reviews. - [Search](/docs/search.md): Choose between one platform - [Errors](/docs/errors.md): Every error type, what it means, and which ones to retry.