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
Python PHP Javascript
Copy 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)
Copy <?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";
}
Copy 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
Python PHP Javascript
Copy 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)
Copy <?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);
?>
Copy 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);
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.
Example: Send a Request with a Webhook
Copy 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)
Copy 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
Trigger : When a new image is added to a designated Google Drive folder.
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
Trigger : Receive a new image through a Telegram Bot.
Action : Process the image using Deep Image AI's enhancement features.
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.