How to extract recipes from TikTok and Instagram links in Python
To extract a recipe from a TikTok or Instagram post in Python, send the post's link to the ClipParse API. It returns the recipe as JSON: the title, ingredients with quantities and units, ordered steps, timings and servings.
You need a ClipParse API key: get a free one at clipparse.com/get-free-key. It takes seconds and doesn't require a credit card.
Building an iOS or Android app? The iOS and Android SDKs are the recommended way to call the API from a mobile app: extraction is more reliable through them.
Requirements
- Python 3.10 or later
- The
requestspackage:pip install requests - A ClipParse API key, in the
CLIPPARSE_API_KEYenvironment variable
Extract a recipe from a link
Send the link to POST https://api.clipparse.com/v1/extract, with your key in the X-API-Key header:
import os
import requests
API_URL = "https://api.clipparse.com/v1/extract"
class ClipParseError(Exception):
def __init__(self, status: int, code: str, message: str | None, retry_after: float | None):
super().__init__(message or f"HTTP {status}: {code}")
self.status = status
self.code = code
self.retry_after = retry_after
@property
def retryable(self) -> bool:
return self.status >= 500 or self.code == "rate_limited"
def extract_recipe(post_url: str) -> dict:
response = requests.post(
API_URL,
headers={"X-API-Key": os.environ["CLIPPARSE_API_KEY"]},
json={"url": post_url},
timeout=60,
)
try:
body = response.json()
except ValueError:
body = {}
if response.ok and body.get("status") in ("success", "no_recipe"):
return body
retry_after = response.headers.get("Retry-After")
raise ClipParseError(
response.status_code,
body.get("code") or ("invalid_request" if response.status_code == 422 else "unexpected_response"),
body.get("message"),
float(retry_after) if retry_after else None,
)
The response's status says what happened. On success, the body carries the recipe. On no_recipe, the post holds no usable recipe, and code says why: no_recipe_found, or multiple_recipes_detected when it holds several recipes in one post. Both come with HTTP 200: a post with no recipe is an expected outcome, not an error.
result = extract_recipe("https://www.tiktok.com/@somecreator/video/1234567890")
if result["status"] == "success":
recipe = result["recipe"]
print(recipe["title"])
for ingredient in recipe["ingredients"]:
print(ingredient["raw"])
for step in recipe["steps"]:
print(step["text"])
else:
print("No recipe:", result["code"])
Handle errors
Every other outcome is an error with a code, raised above as a ClipParseError:
platform_unsupported(400): the link isn't a TikTok or Instagram post.post_unavailable(404): the post was deleted, is private, or doesn't exist. Retrying won't help.unauthorizedorinvalid_key(401),key_revoked(403): a problem with your API key.rate_limited(429): too many requests in a short time. Retry after the number of seconds in theRetry-Afterheader.quota_exceeded(429): the key's allowance is spent until the time inresetsAt.internal_error(500): a transient failure. Retry with backoff.
A value that isn't a URL gets a 422 with a validation error, which extract_recipe reports as invalid_request.
To show a message to your users, map the codes they can act on and treat the rest as a generic failure:
USER_MESSAGES = {
"platform_unsupported": "Only TikTok and Instagram links are supported.",
"invalid_request": "That doesn't look like a link.",
"post_unavailable": "This post was deleted, is private, or doesn't exist.",
"rate_limited": "Too many imports right now. Try again later.",
"quota_exceeded": "Too many imports right now. Try again later.",
}
def user_message(error: ClipParseError) -> str:
return USER_MESSAGES.get(error.code, "Something went wrong. Please try again.")
The API key errors are yours to fix, not the user's: log them, with their message, so you notice. Branch on code, not on message: its wording can change.
Retry what's worth retrying
Only internal_error and rate_limited are worth retrying. This wrapper retries them a few times, waiting for Retry-After when the API gives one and backing off otherwise:
import time
def extract_with_retry(post_url: str, attempts: int = 3) -> dict:
for attempt in range(1, attempts + 1):
try:
return extract_recipe(post_url)
except ClipParseError as error:
wait = error.retry_after or 2**attempt
if not error.retryable or attempt == attempts or wait > 60:
raise
time.sleep(wait)
Use the recipe's fields
The recipe's fields:
title, andlanguage: a short code such as"en".sourceUrl: the post the recipe came from.thumbnailUrl: the post's thumbnail, when there is one. The URL expires, so download the image if you keep the recipe.servings,prepTimeMinutesandcookTimeMinutes, when the post states them.ingredients, in the order the post lists them. Each has aname, aquantityand aunit, theprepnote (such as "finely chopped"), thesectionit belongs to (such as "For the sauce"), andraw: the line exactly as the post wrote it.steps, in order. Each has itstext, adurationMinuteswhen stated, and asection.
Anything the post doesn't state is null in the JSON, so None in Python. For a range such as "2-3 tbsp", quantity is the midpoint and quantityMin and quantityMax hold the ends. unit is one of g, kg, ml, l, tsp, tbsp, cup, pt, qt, gal, oz, lb, pinch or each. each means the ingredient is counted, such as 3 eggs; None means the post gives no unit.
To show an amount, use the range when there is one:
def amount_text(ingredient: dict) -> str | None:
if ingredient["quantity"] is None:
return None
if ingredient["quantityMin"] is not None and ingredient["quantityMax"] is not None:
amount = f"{ingredient['quantityMin']:g}–{ingredient['quantityMax']:g}"
else:
amount = f"{ingredient['quantity']:g}"
if ingredient["unit"] in (None, "each"):
return amount
return f"{amount} {ingredient['unit']}"
Track your allowance
Every response to a request with a valid key reports your allowance in headers: X-Quota-Limit, X-Quota-Used, X-Quota-Remaining, and X-Quota-Reset, the time it renews. X-Credits-Used says what the request itself used. Errors and no_recipe outcomes use no credits.
Every response also carries an X-Request-Id. Log it with failures, and quote it when contacting support.
Get schema.org JSON-LD instead
If your app already imports recipes in the schema.org format, call POST https://api.clipparse.com/v1/extract/schema-org with the same request instead. On success, the body is a schema.org/Recipe object served as application/ld+json. The other outcomes are unchanged, so tell them apart by the Content-Type.
Next steps
- The API reference lists every field and outcome. The OpenAPI spec is at docs.clipparse.com/openapi.json.
- The Node.js guide shows the same calls in JavaScript.
- Pricing covers what each extraction costs and the plans past the free tier.