FastAPI: download YouTube, TikTok and Instagram videos
FastAPI's async handlers pair well with httpx.AsyncClient: resolving a video doesn't block a worker, so one process can serve many concurrent requests.
How it fits together
A shared httpx.AsyncClient is created at startup with the base URL and bearer header. The endpoint forwards the URL, maps errors to HTTPException, and returns a Pydantic model.
FastAPI example
import osfrom contextlib import asynccontextmanagerimport httpxfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, HttpUrlclass Resolved(BaseModel):title: strthumbnail: str | NonedownloadUrl: str@asynccontextmanagerasync def lifespan(app: FastAPI):app.state.cf = httpx.AsyncClient(base_url="https://api.crawlfetch.com",headers={"Authorization": f"Bearer {os.environ['CRAWLFETCH_KEY']}"},timeout=15,)yieldawait app.state.cf.aclose()app = FastAPI(lifespan=lifespan)@app.get("/resolve", response_model=Resolved)async def resolve(url: HttpUrl):r = await app.state.cf.get("/v1/resolve", params={"url": str(url)})if r.status_code != 200:raise HTTPException(r.status_code, "Could not resolve video")return r.json()
Notes for FastAPI
HttpUrlrejects malformed input before you spend a request.- For large batches, use
asyncio.Semaphoreto cap concurrent calls at your plan's limit. - Run long downloads in a background worker (Celery, arq, RQ), not in the request.
FAQ
Why not use requests in FastAPI?
requests is blocking and would tie up the event loop. httpx.AsyncClient keeps endpoints non-blocking.
Related
Last updated 2026-10-25