Dealing with 400: invalid_base64

Fix BackgroundErase invalid_base64 errors by sending a real base64-encoded image string, avoiding malformed payloads, and keeping your JSON or multipart body aligned with the API’s supported fields.

Eric
Written by Eric
Updated in March 2026

A 400 invalid_base64 response means the API received a value in one of the base64 image fields, but that value could not be decoded as valid base64. In practice, this happens before the image is opened with Pillow, so the request fails early if the encoded string itself is malformed.

The good news is that this is usually a request construction problem, not an image-processing problem. Most of the time the issue is one of these: the string was truncated, it contains illegal characters, a file path or URL was sent instead of true base64, or the app wrapped the image data incorrectly before sending it to the API.

Fastest fix: freshly encode one small image to base64, send it in image_base64 in a clean JSON request, and confirm that works before debugging the rest of your app or automation flow.


What this error looks like

A typical response looks like this:

{
  "error": {
    "code": "invalid_base64",
    "message": "image_base64 is not valid base64.",
    "status": 400,
    "request_id": "..."
  }
}

This tells you the failure happened at the base64 decoding step, before the API got far enough to verify whether the decoded bytes were actually a real image.

Data URL prefixes are supported

One useful detail is that the API automatically strips a leading data:image/...;base64, prefix before decoding. That means both of these are valid patterns:

  • Raw base64 only
  • A full data URL string that starts with image metadata

So if your frontend uses canvas exports or browser APIs that naturally produce data URLs, you do not have to strip that prefix yourself first. The API already handles it.

{
  "image_base64": "data:image/png;base64,BASE64_IMAGE_HERE",
  "format": "png"
}

Start with a minimal known-good JSON request

The easiest baseline is a simple JSON request with a freshly encoded image in image_base64. If this works, the API is fine and the issue is in how your app or tool builds the payload.

curl -H 'x-api-key: YOUR_API_KEY' \
-H 'Content-Type: application/json' \
https://api.backgrounderase.com/v2 \
-d '{
  "image_base64": "BASE64_IMAGE_HERE",
  "format": "png",
  "size": "full"
}'

A clean JSON body can look like this:

{
  "image_base64": "BASE64_IMAGE_HERE",
  "format": "png",
  "size": "full",
  "crop": false,
  "despill": false
}

The legacy JSON path also works, but it is mainly useful if you are intentionally using the older image field format:

curl -H 'x-api-key: YOUR_API_KEY' \
-H 'Content-Type: application/json' \
https://api.backgrounderase.com/v2 \
-d '{
  "image": "BASE64_IMAGE_HERE"
}'

Multipart base64 also works

If your stack uses multipart/form-data but still wants to send a base64 string, the API accepts image_base64 and image_file_b64 there too.

curl -H 'x-api-key: YOUR_API_KEY' \
-f https://api.backgrounderase.com/v2 \
-F 'image_base64=BASE64_IMAGE_HERE' \
-F 'format=png' \
-o output.png

Common reasons base64 becomes invalid

In real apps and automations, these are the most common causes of invalid_base64:

  • The string was truncated before it reached the API
  • The value contains spaces, line breaks, or illegal characters
  • A file path or public URL was sent instead of base64 bytes
  • The client wrapped the payload in extra JSON or quotes incorrectly
  • A frontend sent a blob URL rather than file contents
  • A no-code tool transformed the string unexpectedly
  • The image was encoded incorrectly or double-encoded

The BackgroundErase API decodes with strict validation, so even small deviations from true base64 can trigger the error.

Validate the base64 locally first

If you are not sure whether the problem is your encoding step or the API call itself, validate the string locally first. In Python:

import base64

value = "BASE64_IMAGE_HERE"

try:
    decoded = base64.b64decode(value, validate=True)
    print("Valid base64, bytes:", len(decoded))
except Exception as e:
    print("Invalid base64:", e)

If local validation fails, the issue is definitely upstream of the API request.

Encode the image fresh in Python

If you want a clean baseline, encode the file directly from disk and send it immediately:

import base64
import json
import requests

with open("input.jpg", "rb") as f:
    encoded = base64.b64encode(f.read()).decode("utf-8")

payload = {
    "image_base64": encoded,
    "format": "png",
    "size": "full"
}

response = requests.post(
    "https://api.backgrounderase.com/v2",
    headers={
        "x-api-key": "YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    data=json.dumps(payload),
    timeout=120,
)

print(response.status_code)
print(response.text[:1000])

Encode the image fresh in Node.js

In Node.js, the cleanest baseline is to read the file as bytes and call toString("base64"):

import fs from "fs";

const bytes = fs.readFileSync("./input.jpg");
const encoded = bytes.toString("base64");

const response = await fetch("https://api.backgrounderase.com/v2", {
  method: "POST",
  headers: {
    "x-api-key": process.env.BG_ERASE_API_KEY,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    image_base64: encoded,
    format: "png",
    size: "full"
  })
});

console.log(response.status);
console.log(await response.text());

invalid_base64 vs body is not a valid image

This distinction is important. If the string itself is not decodable as base64, you get invalid_base64. But if the string is valid base64 and decodes successfully, the API then tries to open those bytes as an image.

So a second kind of failure can happen later: the base64 may be formally valid, but the decoded bytes are not actually an image. In that case the request can fail later with a different image-decoding error rather than invalid_base64.

Practical takeaway: First make the string valid base64. Then make sure the decoded bytes are really a supported image.

Base64 is convenient, but file upload is usually simpler

Base64 is useful for JSON-first integrations, browser-based workflows, and systems that already store images as encoded strings. But it also creates more ways for the payload to go wrong: truncation, escaping issues, wrong serialization, whitespace, and larger request sizes.

If you control the backend and already have the original file, direct image_file upload is usually the simplest and most reliable path.

Final resolution path

If you are seeing invalid_base64, the cleanest path is:

  • Use a supported base64 field for your request type
  • Freshly encode the image instead of reusing a questionable string
  • Remove truncation, whitespace, and extra wrappers
  • Use a clean JSON or multipart request
  • Validate the base64 locally if needed
  • Retry with one small known-good image first
  • Switch to image_file upload if base64 remains fragile

In most cases, the issue is not the API logic itself. It is how the image string was prepared before it reached the request.