Kotlin Android Background Removal API Integration – ByByBG

Kotlin (Android) Background Removal API Integration

This guide explains how Android developers can integrate the ByByBG Background Removal API into their apps using Kotlin. The example below uses OkHttp, which is widely used in Android projects.

Before You Start

  • Create a ByByBG account
  • Copy your API key from the dashboard
  • Android Studio with Kotlin support

Step 1: Add OkHttp Dependency

Add the following dependency to your build.gradle file:


dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
}
        

Step 2: Add Your API Key

👉 Replace YOUR_API_KEY_HERE with your real API key. This key is required for authentication.


import okhttp3.*

val client = OkHttpClient()

val request = Request.Builder()
    .url("https://bybybg.com/v1/remove-bg")
    .addHeader("X-API-Key", "YOUR_API_KEY_HERE")
    .post(
        MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file",
                "image.png",
                RequestBody.create(
                    "image/png".toMediaTypeOrNull(),
                    imageBytes
                )
            )
            .build()
    )
    .build()
        

Step 3: Execute Request

Execute the request asynchronously and handle the API response.


client.newCall(request).enqueue(object : Callback {

    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    override fun onResponse(call: Call, response: Response) {
        if (response.isSuccessful) {
            val imageBytes = response.body?.bytes()
            // Use the returned PNG bytes
        } else {
            println("API Error: ${response.code}")
        }
    }
})
        

Where to Use This Code

  • Call from ViewModel or Repository layer
  • Do not run network calls on main thread
  • Store API key securely (BuildConfig or env)

Common Errors

  • 401 – API key missing or invalid
  • 429 – Free limit reached
  • 500 – Server error

Best Practices

  • Never hardcode API keys in public repos
  • Validate image size before upload
  • Handle timeouts and retries gracefully