crawlfetch

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 os
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
class Resolved(BaseModel):
title: str
thumbnail: str | None
downloadUrl: str
@asynccontextmanager
async 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,
)
yield
await 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

  • HttpUrl rejects malformed input before you spend a request.
  • For large batches, use asyncio.Semaphore to 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

Add video downloads to your product today.

1,000 credits on signup plus 500 every month. That is roughly 180 YouTube clips to start, with no card.

Create free account