API Documentation
  • Welcome!
  • Quick Start
  • API methods
  • Easy integration
  • Easily Copy Pre-Formatted API Requests for Integration
  • Handling Large File Sets
  • Supported formats
  • Webhooks
  • Common usecases
    • Auto enhance image quality
    • Create business photo or avatar from face image
    • Face swap
    • Create beautiful product photo
    • Genarate image in high resolution
    • Remove background
    • AI Drawing to Image - Doodle
    • Real estate
    • Enhancing documents
    • Car dealer photo
  • Image processing
    • Resize and padding
    • Denoise and sharpen
    • Enhance lighting and colors
    • Enhance face details
    • Background removal and generation
    • Image generation
    • Inpainting and outpainting (uncrop)
    • Frame identification
    • Print
    • Captions
    • Additional parameters
    • Presets
  • Account & settings
    • Account information
  • storages
    • Overview
    • Usage
    • Setup
      • AWS S3
      • OneDrive
      • Dropbox
      • Google Drive
  • Presets
    • E-commerce
    • Real-estate
    • Print/Photo
    • Digital Art
  • Technology
    • Algorithms
    • Upscale
    • Background removal
      • Remove BG recommendation
    • Sharpen & Noise reduction
    • Enhance Lighting
  • FAQ
Powered by GitBook
On this page

Easy integration

PreviousAPI methodsNextEasily Copy Pre-Formatted API Requests for Integration

Last updated 2 months ago

Easy API Integration with Deep Image AI

Deep Image AI makes it easy to process images through a simple API. Follow these steps to use it correctly and avoid common mistakes.


1. Process an Image

There are two processing methods.

The method sends an image for processing and immediately returns job id.

The method sends an image and waits up to 25 seconds for the result. If the image is processed in time, you get a direct link to the final image.

Sending an image with process method and periodically checking the result

import time
import json
from pathlib import Path

from urllib.request import urlretrieve

# using requests library
import requests

API_KEY = REPLACE_WITH_YOUR_API_KEY

headers = {
    'x-api-key': API_KEY,
}

data = {
    "enhancements": ["denoise", "deblur", "light"],
    "width": 2000
}

data_dumped = {"parameters": json.dumps(data)}

with open(YOUR_LOCAL_FILE_TO_SEND, 'rb') as f:
    response = requests.post('https://deep-image.ai/rest_api/process', headers=headers,
                             files={'image': f},
                             data=data_dumped)
    if response.status_code == 200:
        response_json = response.json()
        job_id = response_json["job"]
        result_status = "received"

        while result_status in ['received', 'in_progress', 'not_started']:
            response = requests.get(f'https://deep-image.ai/rest_api/result/{job_id}',
                                    headers=headers)
            response_json = response.json()
            result_status = response_json['status']
            time.sleep(1)
        if result_status == 'complete':
            p = Path(response_json['result_url'])
            urlretrieve(response_json['result_url'], p.name)

<?php

$apiKey = 'REPLACE_WITH_YOUR_API_KEY';
$yourLocalFileToSend = 'path/to/your/image.jpg';

$headers = [
    'x-api-key: ' . $apiKey,
];

$data = [
    "enhancements" => ["denoise", "deblur", "light"],
    "width" => 2000
];

$ch = curl_init();

$curlFile = new CURLFile($yourLocalFileToSend);
$postFields = [
    'image' => $curlFile,
    'parameters' => json_encode($data)
];

curl_setopt($ch, CURLOPT_URL, 'https://deep-image.ai/rest_api/process');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

$response = curl_exec($ch);
curl_close($ch);

$responseJson = json_decode($response, true);
$jobId = $responseJson['job'] ?? null;

if ($jobId) {
    $resultStatus = 'received';
    while (in_array($resultStatus, ['received', 'in_progress', 'not_started'])) {
        sleep(1);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://deep-image.ai/rest_api/result/{$jobId}");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $resultResponse = curl_exec($ch);
        curl_close($ch);
        
        $resultJson = json_decode($resultResponse, true);
        $resultStatus = $resultJson['status'] ?? '';
    }
    
    if ($resultStatus === 'complete') {
        $resultUrl = $resultJson['result_url'] ?? '';
        if ($resultUrl) {
            $fileName = basename($resultUrl);
            file_put_contents($fileName, file_get_contents($resultUrl));
            echo "File downloaded as {$fileName}\n";
        }
    }
} else {
    echo "Error: No job ID received.\n";
}

const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
const FormData = require('form-data');
const { promisify } = require('util');
const streamPipeline = promisify(require('stream').pipeline);

const API_KEY = 'REPLACE_WITH_YOUR_API_KEY';
const YOUR_LOCAL_FILE_TO_SEND = 'path/to/your/image.jpg';

const headers = {
    'x-api-key': API_KEY,
};

const data = {
    "enhancements": ["denoise", "deblur", "light"],
    "width": 2000
};

async function processImage() {
    const formData = new FormData();
    formData.append('image', fs.createReadStream(YOUR_LOCAL_FILE_TO_SEND));
    formData.append('parameters', JSON.stringify(data));

    try {
        const response = await fetch('https://deep-image.ai/rest_api/process', {
            method: 'POST',
            headers: headers,
            body: formData
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const responseJson = await response.json();
        const jobId = responseJson.job;
        let resultStatus = 'received';

        while (["received", "in_progress", "not_started"].includes(resultStatus)) {
            await new Promise(resolve => setTimeout(resolve, 1000));
            const resultResponse = await fetch(`https://deep-image.ai/rest_api/result/${jobId}`, { headers });
            const resultJson = await resultResponse.json();
            resultStatus = resultJson.status;
        }

        if (resultStatus === 'complete') {
            const resultUrl = resultJson.result_url;
            const fileName = path.basename(resultUrl);
            const fileResponse = await fetch(resultUrl);

            if (!fileResponse.ok) throw new Error(`HTTP error while downloading file! status: ${fileResponse.status}`);
            
            const fileStream = fs.createWriteStream(fileName);
            await streamPipeline(fileResponse.body, fileStream);
            console.log(`File downloaded as ${fileName}`);
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

processImage();

Sending an Image with process_result method and periodically checking the result

import time
import json
from pathlib import Path

from urllib.request import urlretrieve

# using requests library
import requests

API_KEY = REPLACE_WITH_YOUR_API_KEY

headers = {
    'x-api-key': API_KEY,
}

data = {
    "enhancements": ["denoise", "deblur", "light"],
    "width": 2000
}

data_dumped = {"parameters": json.dumps(data)}

with open(YOUR_LOCAL_FILE_TO_SEND, 'rb') as f:
    response = requests.post('https://deep-image.ai/rest_api/process_result', headers=headers,
                             files={'image': f},
                             data=data_dumped)
    if response.status_code == 200:
        response_json = response.json()
        if response_json.get('status') == 'complete':
            p = Path(response_json['result_url'])
            urlretrieve(response_json['result_url'], p.name)
        elif response_json['status'] in ['received', 'in_progress', 'not_started']:
            while response_json['status'] in ['received', 'in_progress', 'not_started']:
                response = requests.get(f'https://deep-image.ai/rest_api/result/{response_json["job"]}',
                                        headers=headers)
                response_json = response.json()
                time.sleep(1)
            if response_json['status'] == 'complete':
                p = Path(response_json['result_url'])
                urlretrieve(response_json['result_url'], p.name)

<?php

$API_KEY = 'REPLACE_WITH_YOUR_API_KEY';
$YOUR_LOCAL_FILE_TO_SEND = 'path/to/your/image.jpg';

$headers = [
    'x-api-key: ' . $API_KEY
];

$data = [
    "enhancements" => ["denoise", "deblur", "light"],
    "width" => 2000
];

function processImage($filePath, $headers, $data) {
    try {
        // Prepare the file upload
        $postData = [
            'image' => new CURLFile($filePath),
            'parameters' => json_encode($data)
        ];

        // Initialize cURL for processing
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://deep-image.ai/rest_api/process_result');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            throw new Exception('cURL error: ' . curl_error($ch));
        }
        
        curl_close($ch);
        
        $responseJson = json_decode($response, true);
        
        if (!$responseJson) {
            throw new Exception("Error processing image: " . $response);
        }
        
        if ($responseJson['status'] === 'complete') {
            downloadFile($responseJson['result_url']);
        } else if (in_array($responseJson['status'], ['received', 'in_progress', 'not_started'])) {
            while (in_array($responseJson['status'], ['received', 'in_progress', 'not_started'])) {
                sleep(1);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "https://deep-image.ai/rest_api/result/{$responseJson['job']}");
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                
                $response = curl_exec($ch);
                $responseJson = json_decode($response, true);
                curl_close($ch);
            }
            
            if ($responseJson['status'] === 'complete') {
                downloadFile($responseJson['result_url']);
            }
        }
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

function downloadFile($url) {
    try {
        $fileName = basename($url);
        $fileContent = file_get_contents($url);
        
        if ($fileContent === false) {
            throw new Exception("Failed to download file from: " . $url);
        }
        
        file_put_contents($fileName, $fileContent);
        echo "File downloaded as " . $fileName . "\n";
        
    } catch (Exception $e) {
        echo "Error downloading file: " . $e->getMessage() . "\n";
    }
}

// Execute the function
processImage($YOUR_LOCAL_FILE_TO_SEND, $headers, $data);

?>

const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
const FormData = require('form-data');

const API_KEY = 'REPLACE_WITH_YOUR_API_KEY';
const YOUR_LOCAL_FILE_TO_SEND = 'path/to/your/image.jpg';

const headers = {
    'x-api-key': API_KEY,
};

const data = {
    "enhancements": ["denoise", "deblur", "light"],
    "width": 2000
};

async function processImage() {
    const formData = new FormData();
    formData.append('image', fs.createReadStream(YOUR_LOCAL_FILE_TO_SEND));
    formData.append('parameters', JSON.stringify(data));

    let response = await fetch('https://deep-image.ai/rest_api/process_result', {
        method: 'POST',
        headers: headers,
        body: formData
    });
    
    if (!response.ok) {
        console.error("Error processing image", await response.text());
        return;
    }
    
    let responseJson = await response.json();
    
    if (responseJson.status === 'complete') {
        await downloadFile(responseJson.result_url);
    } else if (["received", "in_progress", "not_started"].includes(responseJson.status)) {
        while (["received", "in_progress", "not_started"].includes(responseJson.status)) {
            await new Promise(resolve => setTimeout(resolve, 1000));
            response = await fetch(`https://deep-image.ai/rest_api/result/${responseJson.job}`, { headers: headers });
            responseJson = await response.json();
        }
        if (responseJson.status === 'complete') {
            await downloadFile(responseJson.result_url);
        }
    }
}

async function downloadFile(url) {
    const fileName = path.basename(url);
    const response = await fetch(url);
    const buffer = await response.buffer();
    fs.writeFileSync(fileName, buffer);
    console.log(`File downloaded as ${fileName}`);
}

processImage().catch(console.error);

If you don’t get a result URL, don’t send the image again! Use the job ID to check the status instead.


2. Get results faster with webhooks (Recommended)

Instead of checking the status manually, you can set up a webhook. This means Deep Image AI will send you the result automatically when the image is ready.

Why use webhooks?

  • No need to keep checking the status.

  • The result is sent automatically when ready.

Example: Send a Request with a Webhook

payload = {
    "webhook_url": "https://your-server.com:5000/deep-image-webhook",
    "enhancements": ["denoise", "deblur", "light"],
    "width": 2000
}

data_dumped = {"parameters": json.dumps(payload)}

with open("YOUR_LOCAL_FILE_TO_SEND", "rb") as f:
    response = requests.post("https://deep-image.ai/rest_api/process", headers=headers,
                             files={"image": f}, data=data_dumped)

print(response.json())  # Shows job ID

Example: Receiving the Webhook (Flask)

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/deep-image-webhook", methods=["POST"])
def webhook():
    data = request.json
    print("Image is ready:", data["result_url"])
    return jsonify({"status": "received"}), 200

app.run(port=5000)

3. Automate Workflows with Zapier Integration

Zapier enables you to connect Deep Image AI with thousands of other applications, automating tasks seamlessly. For example, you can set up a workflow where images uploaded to a specific folder in Google Drive are automatically enhanced using Deep Image AI.

✅ Example: Automating Image Enhancement with Zapier

  1. Trigger: When a new image is added to a designated Google Drive folder.

  2. Action: Use Deep Image AI to enhance the image automatically.

This setup ensures that every image added to your folder is processed without manual intervention.

Resources:


4. Enhance Automation with Make (Integromat) Integration

Make allows you to build and automate complex workflows by connecting Deep Image AI with numerous other apps. For instance, you can create a scenario where images from a Telegram Bot are automatically processed and stored in Dropbox.

✅ Example: Processing Images via Make

  1. Trigger: Receive a new image through a Telegram Bot.

  2. Action: Process the image using Deep Image AI's enhancement features.

  3. Action: Save the enhanced image to a Dropbox folder.

This workflow automates the entire process from image reception to storage.

Resources:


Summary: Leveraging Automation Platforms

  • Zapier Integration: Automate tasks by connecting Deep Image AI with various apps, enabling workflows like automatic image enhancement upon upload.

  • Make Integration: Design intricate scenarios that process images through Deep Image AI and interact with multiple applications, enhancing efficiency.

By integrating Deep Image AI with these platforms, you can significantly streamline your image processing tasks and improve productivity.

Deep Image AI Zapier Integrations: Explore various integration possibilities -

Integration Guide: Step-by-step instructions on creating your first Zap with Deep Image AI -

Deep Image AI Make Integrations: Discover integration options and modules available -

Integration Guide: Learn how to integrate photo enhancements with other tools using Make -

https://zapier.com/apps/deep-image/integrations
https://deep-image.ai/blog/deep-image-now-fully-integrated-with-zapier-quick-guide-for-your-first-zap
https://www.make.com/en/integrations/deep-image-ai
https://deep-image.ai/blog/how-to-use-make-com-to-integrate-photo-enhancements-with-other-tools
process
process_result