Node.js Integration

In this tutorial, I will show you how you can integrate the PhotoRoom API into a Node.js 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:

How 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 https = require('https');
const fs = require('fs');

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

function removeBackground(imagePath, savePath) {
    return new Promise((resolve, reject) => {
        const boundary = '--------------------------' + Date.now().toString(16);
        
        const postOptions = {
            hostname: 'sdk.photoroom.com',
            path: '/v1/segment',
            method: 'POST',
            headers: {
                'Content-Type': `multipart/form-data; boundary=${boundary}`,
                'X-API-Key': apiKey
            }
        };

        const req = https.request(postOptions, (res) => {
            // Check if the response is an image
            const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(res.headers['content-type']);

            if (!isImage) {
                let errorData = '';
                res.on('data', (chunk) => errorData += chunk);
                res.on('end', () => reject(new Error(`Expected an image response, but received: ${errorData}`)));
                return;
            }

            // Create a write stream to save the image
            const fileStream = fs.createWriteStream(savePath);
            res.pipe(fileStream);

            fileStream.on('finish', () => {
                resolve(`Image saved to ${savePath}`);
            });

            fileStream.on('error', (error) => {
                reject(new Error(`Failed to save the image: ${error.message}`));
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        // Write form data
        req.write(`--${boundary}\r\n`);
        req.write(`Content-Disposition: form-data; name="image_file"; filename="${imagePath.split('/').pop()}"\r\n`);
        req.write('Content-Type: image/jpeg\r\n\r\n'); // assuming JPEG, adjust if another format is used

        const uploadStream = fs.createReadStream(imagePath);
        uploadStream.on('end', () => {
            req.write('\r\n');
            req.write(`--${boundary}--\r\n`);
            req.end();
        });
        
        uploadStream.pipe(req, { end: false });
    });
}

module.exports = removeBackground;

Step 3: Call the API

Now it's time to call the API in your code! Just use the function removeBackground() and pass as arguments both the path of the original image and the path where the result image should be saved.

const removeBackground = require('./remove-background');

const imagePath = './path/to/your/image.jpg';
const savePath = './path/where/you/want/to/save/response.jpg';

removeBackground(imagePath, savePath)
    .then(message => {
        console.log(message);
    })
    .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 Node.js project 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