Image Background Removal API Tutorial

This guide will walk you through using the Easy-Peasy.ai API to programmatically remove the background from an image. The process involves two main steps:

  1. Submitting your image for processing: This is an asynchronous request that tells our system to start working on your image.
  2. Retrieving the processed image: After a short delay, you’ll make a second request to get the URL of the image with its background removed.

Authentication

All API requests must be authenticated using an API key. You’ll need to include your API key in the x-api-key header for every request.

x-api-key: YOUR_API_KEY

Replace YOUR_API_KEY with your actual API key. You can find your API key in your Easy-Peasy.ai account settings.

Step 1: Initiate Background Removal

To start the background removal process, you’ll send a POST request to the /api/generate-image endpoint.

Endpoint:

POST https://easy-peasy.ai/api/generate-image

Headers:

  • accept: application/json
  • x-api-key: YOUR_API_KEY
  • Content-Type: application/json

Request Body (JSON):

  • image (string, required): The publicly accessible URL of the image you want to process.
  • action (string, required): Specifies the operation to perform. For background removal, use "Remove Background".

Example cURL Request:

curl -X POST "https://easy-peasy.ai/api/generate-image" \
  -H "accept: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://media.easy-peasy.ai/27feb2bb-aeb4-4a83-9fb6-8f3f2a15885e/2b33ab2e-cf90-4bec-a1cc-1abc9160df53.png",
    "action": "Remove Background"
  }'

Expected Response (200 OK / 201 Created):

The API will respond immediately, confirming that your request has been received and queued for processing. The response will include an id for the image job and an initially empty image_url.

[
  {
    "id": 2323596,
    "image_url": "",
    "prompt": "Remove background",
    "model": "Img2Img",
    "used_credits": 1
  }
]

Important: Note down the id from this response (e.g., 2323596). You’ll need it for the next step. The image_url is empty at this stage because the processing is asynchronous and takes a few moments to complete.

Step 2: Retrieve the Processed Image

Since the background removal is asynchronous, you’ll need to wait a brief period (e.g., 5-10 seconds) before attempting to retrieve the result. Then, send a GET request to the /api/get-image endpoint, using the id you received in Step 1.

Endpoint:

GET https://easy-peasy.ai/api/get-image

Headers:

  • accept: application/json
  • x-api-key: YOUR_API_KEY

Query Parameters:

  • imageId (number, required): The id of the image job, obtained from the response in Step 1.

Example cURL Request:

Replace YOUR_IMAGE_ID_HERE with the actual id (e.g., 2323596).

curl -X GET "https://easy-peasy.ai/api/get-image?imageId=YOUR_IMAGE_ID_HERE" \
  -H "accept: application/json" \
  -H "x-api-key: YOUR_API_KEY"

Expected Response (200 OK):

If the processing is complete, the response will contain the details of your image, including the image_url where the background-removed image is hosted.

{
  "id": 2323596,
  "image_url": "https://media.easy-peasy.ai/27feb2bb-aeb4-4a83-9fb6-8f3f2a15885e/043bb4f7-5af3-48c7-a917-83e088ed6372.png",
  "created_at": "2025-05-21T12:44:40.96729+00:00",
  "used_credits": 1
}

You can now use the image_url to access your processed image.

What if the image isn’t ready?

If you request the image before processing is complete, the image_url might still be empty, or you might receive a response indicating it’s still processing. It’s recommended to implement a short delay or a polling mechanism (with reasonable intervals and a maximum number of retries) if you need to automate this process. The examples below include a simple delay.

Code Examples

Below are examples of how to implement this two-step process in Node.js, PHP, and Python.

Node.js (using axios)

First, make sure you have axios installed:

npm install axios

Then, you can use the following script:

// Node.js Example (using axios)
const axios = require('axios');

const apiKey = 'YOUR_API_KEY'; // Replace with your API key
const baseApiUrl = 'https://easy-peasy.ai/api';

// Step 1: Initiate Background Removal
async function initiateBackgroundRemoval(imageUrl) {
  console.log('Step 1: Initiating background removal...');
  try {
    const response = await axios.post(
      `${baseApiUrl}/generate-image`,
      {
        image: imageUrl,
        action: 'Remove Background'
      },
      {
        headers: {
          accept: 'application/json',
          'x-api-key': apiKey,
          'Content-Type': 'application/json',
        },
      },
    );
    // Assuming the response is an array with one object, as per the cURL example
    if (response.data && response.data.length > 0 && response.data[0].id) {
      const imageId = response.data[0].id;
      console.log(`Background removal initiated. Image ID: ${imageId}`);
      return imageId;
    } else {
      console.error(
        'Error: Could not find image ID in response.',
        response.data,
      );
      return null;
    }
  } catch (error) {
    console.error('Error initiating background removal:');
    if (error.response) {
      console.error(`Status: ${error.response.status}`);
      console.error('Data:', error.response.data);
    } else {
      console.error(error.message);
    }
    return null;
  }
}

// Step 2: Retrieve the Processed Image
async function getProcessedImage(imageId) {
  console.log(`\nStep 2: Retrieving processed image for ID: ${imageId}...`);
  try {
    // Wait for a few seconds (e.g., 5-10 seconds) for processing
    const delayInMilliseconds = 7000; // Adjust as needed
    console.log(`Waiting for ${delayInMilliseconds / 1000} seconds...`);
    await new Promise((resolve) => setTimeout(resolve, delayInMilliseconds));

    const response = await axios.get(
      `${baseApiUrl}/get-image?imageId=${imageId}`,
      {
        headers: {
          accept: 'application/json',
          'x-api-key': apiKey,
        },
      },
    );
    console.log('Processed image data:', response.data);
    if (response.data.image_url) {
      console.log(
        `Successfully retrieved! Processed Image URL: ${response.data.image_url}`,
      );
    } else {
      console.log(
        'Image processing might still be in progress or an issue occurred. The image_url is not yet available.',
      );
    }
    return response.data;
  } catch (error) {
    console.error('Error retrieving processed image:');
    if (error.response) {
      console.error(`Status: ${error.response.status}`);
      console.error('Data:', error.response.data);
    } else {
      console.error(error.message);
    }
    return null;
  }
}

// --- Main execution ---
async function main() {
  const imageUrlToProcess =
    'https://media.easy-peasy.ai/27feb2bb-aeb4-4a83-9fb6-8f3f2a15885e/2b33ab2e-cf90-4bec-a1cc-1abc9160df53.png'; // Replace with your image URL

  const imageId = await initiateBackgroundRemoval(imageUrlToProcess);

  if (imageId) {
    await getProcessedImage(imageId);
  } else {
    console.log('Could not proceed to get the image as initiation failed.');
  }
}

main();

PHP (using cURL)

<?php
// PHP Example (using cURL)

$apiKey = 'YOUR_API_KEY'; // Replace with your API key
$baseApiUrl = 'https://easy-peasy.ai/api';

// Step 1: Initiate Background Removal
function initiateBackgroundRemoval($imageUrl, $apiKey, $baseApiUrl) {
    echo "Step 1: Initiating background removal...\n";
    $apiUrl = $baseApiUrl . '/generate-image';
    $postData = json_encode([
        'image' => $imageUrl,
        'action' => 'Remove Background'
    ]);

    $headers = [
        'accept: application/json',
        'x-api-key: ' . $apiKey,
        'Content-Type: application/json'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        echo "cURL Error during initiation: " . $error . "\n";
        return null;
    }

    // Assuming the response is an array with one object, as per the cURL example
    if ($httpCode == 200 || $httpCode == 201) { // 201 if resource created
        $responseData = json_decode($response, true);
        if (is_array($responseData) && count($responseData) > 0 && isset($responseData[0]['id'])) {
            $imageId = $responseData[0]['id'];
            echo "Background removal initiated. Image ID: " . $imageId . "\n";
            return $imageId;
        } else {
            echo "Error: Could not find image ID in response.\n";
            print_r($responseData);
            return null;
        }
    } else {
        echo "Error initiating background removal. HTTP Code: " . $httpCode . "\n";
        echo "Response: " . $response . "\n";
        return null;
    }
}

// Step 2: Retrieve the Processed Image
function getProcessedImage($imageId, $apiKey, $baseApiUrl) {
    echo "\nStep 2: Retrieving processed image for ID: " . $imageId . "...\n";
    $apiUrl = $baseApiUrl . '/get-image?imageId=' . $imageId;
    $headers = [
        'accept: application/json',
        'x-api-key: ' . $apiKey
    ];

    // Wait for a few seconds (e.g., 5-10 seconds) for processing
    $delayInSeconds = 7; // Adjust as needed
    echo "Waiting for " . $delayInSeconds . " seconds...\n";
    sleep($delayInSeconds);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        echo "cURL Error during retrieval: " . $error . "\n";
        return null;
    }

    if ($httpCode == 200) {
        $responseData = json_decode($response, true);
        echo "Processed image data:\n";
        print_r($responseData);
        if (isset($responseData['image_url']) && !empty($responseData['image_url'])) {
            echo "Successfully retrieved! Processed Image URL: " . $responseData['image_url'] . "\n";
        } else {
            echo "Image processing might still be in progress or an issue occurred. The image_url is not yet available.\n";
        }
        return $responseData;
    } else {
        echo "Error retrieving processed image. HTTP Code: " . $httpCode . "\n";
        echo "Response: " . $response . "\n";
        return null;
    }
}

// --- Main execution ---
$imageUrlToProcess = 'https://media.easy-peasy.ai/27feb2bb-aeb4-4a83-9fb6-8f3f2a15885e/2b33ab2e-cf90-4bec-a1cc-1abc9160df53.png'; // Replace with your image URL

$imageId = initiateBackgroundRemoval($imageUrlToProcess, $apiKey, $baseApiUrl);

if ($imageId !== null) {
    getProcessedImage($imageId, $apiKey, $baseApiUrl);
} else {
    echo "Could not proceed to get the image as initiation failed.\n";
}

?>

Python (using requests)

First, make sure you have the requests library installed:

pip install requests

Then, use the following script:

# Python Example (using requests)
import requests
import json
import time

API_KEY = 'YOUR_API_KEY'  # Replace with your API key
BASE_API_URL = 'https://easy-peasy.ai/api'

# Step 1: Initiate Background Removal
def initiate_background_removal(image_url):
    print("Step 1: Initiating background removal...")
    api_endpoint = f"{BASE_API_URL}/generate-image"
    payload = {
        'image': image_url,
        'action': 'Remove Background'
    }
    headers = {
        'accept': 'application/json',
        'x-api-key': API_KEY,
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(api_endpoint, headers=headers, data=json.dumps(payload))
        response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)

        response_data = response.json()
        # Assuming the response is an array with one object, as per the cURL example
        if response_data and isinstance(response_data, list) and len(response_data) > 0 and response_data[0].get('id'):
            image_id = response_data[0]['id']
            print(f"Background removal initiated. Image ID: {image_id}")
            return image_id
        else:
            print("Error: Could not find image ID in response.")
            print("Response data:", response_data)
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error initiating background removal: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Status Code: {e.response.status_code}")
            print(f"Response content: {e.response.text}")
        return None

# Step 2: Retrieve the Processed Image
def get_processed_image(image_id):
    print(f"\nStep 2: Retrieving processed image for ID: {image_id}...")
    api_endpoint = f"{BASE_API_URL}/get-image?imageId={image_id}"
    headers = {
        'accept': 'application/json',
        'x-api-key': API_KEY
    }

    # Wait for a few seconds (e.g., 5-10 seconds) for processing
    delay_in_seconds = 7  # Adjust as needed
    print(f"Waiting for {delay_in_seconds} seconds...")
    time.sleep(delay_in_seconds)

    try:
        response = requests.get(api_endpoint, headers=headers)
        response.raise_for_status()

        response_data = response.json()
        print("Processed image data:", response_data)
        if response_data.get('image_url'):
            print(f"Successfully retrieved! Processed Image URL: {response_data['image_url']}")
        else:
            print("Image processing might still be in progress or an issue occurred. The image_url is not yet available.")
        return response_data
    except requests.exceptions.RequestException as e:
        print(f"Error retrieving processed image: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Status Code: {e.response.status_code}")
            print(f"Response content: {e.response.text}")
        return None

# --- Main execution ---
if __name__ == "__main__":
    image_url_to_process = 'https://media.easy-peasy.ai/27feb2bb-aeb4-4a83-9fb6-8f3f2a15885e/2b33ab2e-cf90-4bec-a1cc-1abc9160df53.png'  # Replace with your image URL

    retrieved_image_id = initiate_background_removal(image_url_to_process)

    if retrieved_image_id:
        get_processed_image(retrieved_image_id)
    else:
        print("Could not proceed to get the image as initiation failed.")

Error Handling

  • 401 Unauthorized: Your API key is missing, invalid, or your account has an issue.
  • 400 Bad Request: The request was malformed (e.g., missing required fields, invalid image URL). The response body may contain more details.
  • 404 Not Found: If, in Step 2, the imageId is incorrect or the image job doesn’t exist.
  • 429 Too Many Requests: If you exceed rate limits.
  • 5xx Server Errors: If something goes wrong on our end, please try again after a short delay.

Next Steps

You can integrate this two-step process into your applications to automate background removal for your images. Remember to handle potential delays and errors gracefully.

For other image generation and manipulation tasks, please refer to our complete API documentation.


Create Faster With AI.
Try it Risk-Free.

Stop wasting time and start creating high-quality content immediately with power of generative AI.

App screenshot

More Stories