How to import recipes from TikTok and Instagram links in an Android app
To import a recipe from a TikTok or Instagram post into an Android app, pass the post's link to the ClipParse Android SDK. It returns the recipe as structured data: 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.
For a complete app built from this guide's code, see tiktok-instagram-recipe-import-compose on GitHub: a Jetpack Compose app that receives links from the share sheet.
Requirements
- Android 6.0 (API level 23) or later
- Kotlin 2.0 or later
- A ClipParse API key
Add the SDK
The SDK is on Maven Central. Add it to your app module's build.gradle.kts:
dependencies {
implementation("com.clipparse:clipparse-android-sdk:1.2.0")
}
The code in this guide needs 1.2.0 or later. The SDK's changelog lists the latest version. The SDK declares the one permission it uses, INTERNET, in its own manifest.
Extract a recipe from a link
Create a client with a Context and your API key, then call extract with the post's URL. extract is a suspending function: call it from a coroutine. It is safe to call from the main thread.
import com.clipparse.sdk.ClipParseClient
import com.clipparse.sdk.model.ExtractionResult
val client = ClipParseClient(context, apiKey = "<your API key>")
when (val result = client.extract("https://www.tiktok.com/@somecreator/video/1234567890")) {
is ExtractionResult.Success -> {
val recipe = result.recipe
println(recipe.title)
recipe.ingredients.forEach { println(it.raw) }
recipe.steps.forEach { println(it.text) }
}
is ExtractionResult.NoRecipe -> println("No recipe found: ${result.reason}")
}
ExtractionResult has two outcomes: Success with the recipe, or NoRecipe when the post holds no usable recipe. A post with no recipe is an expected outcome, not an error. NoRecipe carries a reason: NoRecipeReason.NoRecipeFound when the post holds no recipe, or NoRecipeReason.MultipleRecipesDetected when it holds several recipes in one post.
The client reads your app's package name from the Context and doesn't keep a reference to it, so any context works.
Wire it into a ViewModel
A ViewModel that imports a link and exposes the state to your UI:
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.clipparse.sdk.ClipParseClient
import com.clipparse.sdk.ClipParseException
import com.clipparse.sdk.model.ExtractionResult
import com.clipparse.sdk.model.NoRecipeReason
import com.clipparse.sdk.model.Recipe
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
sealed interface ImportState {
data object Idle : ImportState
data object Loading : ImportState
data class Imported(val recipe: Recipe) : ImportState
data class Failed(val message: String) : ImportState
}
class RecipeImportViewModel(application: Application) : AndroidViewModel(application) {
private val client = ClipParseClient(application, apiKey = "<your API key>")
private val _state = MutableStateFlow<ImportState>(ImportState.Idle)
val state: StateFlow<ImportState> = _state.asStateFlow()
fun importRecipe(link: String) {
_state.value = ImportState.Loading
viewModelScope.launch {
_state.value = try {
when (val result = client.extract(link.trim())) {
is ExtractionResult.Success -> ImportState.Imported(result.recipe)
is ExtractionResult.NoRecipe ->
if (result.reason == NoRecipeReason.MultipleRecipesDetected) {
ImportState.Failed("This post has more than one recipe.")
} else {
ImportState.Failed("We couldn't find a recipe in this post.")
}
}
} catch (e: ClipParseException) {
ImportState.Failed(importErrorMessage(e))
}
}
}
}
Handle errors
Failures throw a ClipParseException. Its code says what went wrong. Turn it into a message for the user:
import android.util.Log
import com.clipparse.sdk.ClipParseErrorCode
import com.clipparse.sdk.ClipParseException
fun importErrorMessage(e: ClipParseException): String = when (e.code) {
ClipParseErrorCode.PlatformUnsupported -> "Only TikTok and Instagram links are supported."
ClipParseErrorCode.InvalidRequest -> "That doesn't look like a link."
ClipParseErrorCode.PostUnavailable -> "This post was deleted, is private, or doesn't exist."
ClipParseErrorCode.Unauthorized,
ClipParseErrorCode.InvalidApiKey,
ClipParseErrorCode.ApiKeyRevoked -> {
Log.w("RecipeImport", "ClipParse API key error", e)
"Recipe import isn't available right now."
}
ClipParseErrorCode.RateLimited,
ClipParseErrorCode.QuotaExceeded -> "Too many imports right now. Try again later."
ClipParseErrorCode.Network -> "Check your connection and try again."
else -> "Something went wrong. Please try again."
}
Always keep the else branch: new error codes can be added, and the SDK passes on a code it doesn't know yet as is.
The API key errors (Unauthorized, InvalidApiKey, ApiKeyRevoked) are yours to fix, not the user's: log them so you notice. RateLimited and QuotaExceeded carry a retryAfter duration; for QuotaExceeded it is null when the allowance doesn't renew. When isRetryable is true, such as for a dropped connection, the same call is safe to retry. requestId identifies the failed request: quote it when contacting support.
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. For a range such as "2-3 tbsp", quantity is the midpoint and quantityMin and quantityMax hold the ends. unit is IngredientUnit.Each for counted ingredients such as 3 eggs, and null when the post gives no unit.
To show an amount, use the range when there is one:
import com.clipparse.sdk.model.Ingredient
import com.clipparse.sdk.model.IngredientUnit
import java.text.DecimalFormat
private val number = DecimalFormat("0.##")
fun amountText(ingredient: Ingredient): String? {
val quantity = ingredient.quantity ?: return null
val low = ingredient.quantityMin
val high = ingredient.quantityMax
val amount = if (low != null && high != null) {
"${number.format(low)}–${number.format(high)}"
} else {
number.format(quantity)
}
val unit = ingredient.unit
return if (unit == null || unit == IngredientUnit.Each) amount else "$amount ${unit.raw}"
}
Accept links from the share sheet
People find recipes in the TikTok and Instagram apps, so the smoothest way in is the share sheet: the user taps Share on a post and picks your app. Declare an activity that accepts shared text in your AndroidManifest.xml:
<activity
android:name=".ImportActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
Apps share the link as text, sometimes with other words around it, so pick the URL out of the text:
import android.content.Intent
import android.util.Patterns
val sharedText = intent.takeIf { it.action == Intent.ACTION_SEND }
?.getStringExtra(Intent.EXTRA_TEXT)
val link = sharedText
?.let { Patterns.WEB_URL.matcher(it) }
?.takeIf { it.find() }
?.group()
if (link != null) {
viewModel.importRecipe(link)
}
Next steps
- The example app is this guide's code as a complete app, ready to run.
- The API reference lists every field and outcome.
- The ClipParse Android SDK repository has the changelog, and
DATA_SAFETY.md, which helps you fill in Google Play's Data safety form. - Pricing covers what each import costs and the plans past the free tier.