Web Integration

Tutorials Web Integration

In this tutorial, I will show you how you can integrate the PhotoRoom API into a JavaScript or TypeScript codebase in just a few minutes.

Step 1: Get Your API Key

The first thing you need to do is get your API key. Here are the steps you'll need to follow:

pageHow can I get my API key?

Step 2: Use Our Sample Code

Visit PhotoRoom’s GitHub to find a sample code that's ready to use.

Simply copy and paste the code into your project, and update the placeholder with your own API key.

const url = 'https://sdk.photoroom.com/v1/segment';

// Please replace with your own apiKey
const apiKey = "YOUR_API_KEY_HERE";

export async function removeBackground(imageFile: File): Promise<Blob> {
    const formData = new FormData();
    formData.append('image_file', imageFile);

    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'X-Api-Key': apiKey
        },
        body: formData
    });

    if (!response.ok) {
        console.error(response.json())
        throw new Error('Network response was not ok');
    }

    const imageBlob: Blob = await response.blob();

    return imageBlob;
}

Warning: Please be aware that this will make your API key accessible to anyone browsing your website. If your website is public, we recommend calling our API through a proxy that you control (Firebase / Google functions, AWS lambda).

Step 3: Call the API

Now it's time to call the API in your code! Just use the function removeBackground() and pass in the file your user has selected.

The function will return a Blob containing a new image with the background removed.

import { removeBackground } from './remove-background.js';

const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const displayImage = document.getElementById('displayImage') as HTMLImageElement;

fileInput.addEventListener('change', async () => {
    const files = fileInput.files;
    if (files && files.length > 0) {
        try {
            const imageBlob = await removeBackground(files[0]); // 👈 API call is here
            const objectURL = URL.createObjectURL(imageBlob);
            displayImage.src = objectURL;
        } catch (error) {
            console.error('Error:', error);
        }
    }
});

You're done!

That's it! With just these three easy steps, you can integrate the PhotoRoom Background Removal API into your web app and provide your users with high-quality images with clean backgrounds.

According to resellers who use the PhotoRoom app, this feature can increase sales by 20 up to 100%.

If you want to learn more about the PhotoRoom API and get your API key, visit https://www.photoroom.com/api.

Last updated