# 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](https://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](https://github.com/clipparse/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`:

```kotlin
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](https://github.com/clipparse/clipparse-android-sdk/blob/main/CHANGELOG.md)
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.

```kotlin
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:

```kotlin
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:

```kotlin
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`, and `language`: 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`, `prepTimeMinutes` and `cookTimeMinutes`, when the post states
  them.
- `ingredients`, in the order the post lists them. Each has a `name`, a
  `quantity` and a `unit`, the `prep` note (such as "finely chopped"), the
  `section` it belongs to (such as "For the sauce"), and `raw`: the line
  exactly as the post wrote it.
- `steps`, in order. Each has its `text`, a `durationMinutes` when stated,
  and a `section`.

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:

```kotlin
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`:

```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:

```kotlin
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](https://github.com/clipparse/tiktok-instagram-recipe-import-compose)
  is this guide's code as a complete app, ready to run.
- The [API reference](https://docs.clipparse.com/) lists every field and
  outcome.
- The [ClipParse Android SDK](https://github.com/clipparse/clipparse-android-sdk)
  repository has the changelog, and `DATA_SAFETY.md`, which helps you fill in
  Google Play's Data safety form.
- [Pricing](https://clipparse.com/pricing) covers what each import costs and
  the plans past the free tier.
