← Back to Blog
Tutorial2025-11-2910 min read

How to Integrate AI Image API into Your Application

Step-by-step guide to integrating Imagify's AI image generation API into your web, mobile, or desktop application.

By Imagify Team

How to Integrate AI Image API into Your Application

Integrating AI image generation into your application is easier than you might think. This guide walks you through the process step by step.

Prerequisites

Before you begin, you'll need:

  • An Imagify account (sign up here)
  • Your API key (found in your dashboard)
  • Basic knowledge of HTTP requests
  • Your application's codebase

Step 1: Get Your API Key

1. Log in to your Imagify dashboard

2. Navigate to the API section

3. Copy your API key

4. Store it securely (use environment variables, never commit to version control)

Step 2: Make Your First API Call

Using JavaScript/Node.js

async function generateImage(prompt, size = '1024x1024', style = 'standard') {
  const response = await fetch('https://api.imagify.ca/api/images/generate', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.IMAGIFY_API_KEY, // Use environment variable
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      prompt: prompt,
      size: size,
      style: style
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || 'Failed to generate image');
  }

  const data = await response.json();
  return data.image.url;
}

// Usage
try {
  const imageUrl = await generateImage('A serene mountain landscape at sunset');
  console.log('Generated image:', imageUrl);
} catch (error) {
  console.error('Error:', error.message);
}

Using Python

import requests
import os

def generate_image(prompt, size='1024x1024', style='standard'):
    url = 'https://api.imagify.ca/api/images/generate'
    headers = {
        'X-API-Key': os.getenv('IMAGIFY_API_KEY'),  # Use environment variable
        'Content-Type': 'application/json'
    }
    data = {
        'prompt': prompt,
        'size': size,
        'style': style
    }
    
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    
    return response.json()['image']['url']

# Usage
try:
    image_url = generate_image('A futuristic cityscape at night')
    print(f'Generated image: {image_url}')
except requests.exceptions.RequestException as e:
    print(f'Error: {e}')

Using cURL

curl -X POST https://api.imagify.ca/api/images/generate \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A beautiful sunset over the ocean",
    "size": "1024x1024",
    "style": "vivid"
  }'

Step 3: Handle Responses

The API returns a JSON response with the following structure:

{
  "success": true,
  "image": {
    "id": "image_id",
    "url": "https://...",
    "prompt": "Your prompt",
    "size": "1024x1024",
    "style": "standard",
    "createdAt": "2024-12-01T10:30:00Z"
  },
  "credits_remaining": 9
}

Step 4: Error Handling

Always implement proper error handling:

async function generateImageWithErrorHandling(prompt) {
  try {
    const response = await fetch('https://api.imagify.ca/api/images/generate', {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.IMAGIFY_API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ prompt })
    });

    if (response.status === 401) {
      throw new Error('Invalid API key');
    } else if (response.status === 402) {
      throw new Error('Insufficient credits. Please purchase more.');
    } else if (response.status === 429) {
      throw new Error('Rate limit exceeded. Please wait before trying again.');
    } else if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || 'Failed to generate image');
    }

    const data = await response.json();
    return data.image.url;
  } catch (error) {
    console.error('Image generation error:', error);
    // Handle error in your UI
    throw error;
  }
}

Step 5: Display Generated Images

In a Web Application

async function displayGeneratedImage(prompt) {
  try {
    const imageUrl = await generateImage(prompt);
    
    // Create image element
    const img = document.createElement('img');
    img.src = imageUrl;
    img.alt = prompt;
    img.className = 'generated-image';
    
    // Add to page
    document.getElementById('image-container').appendChild(img);
  } catch (error) {
    alert('Failed to generate image: ' + error.message);
  }
}

In a React Component

import { useState } from 'react';

function ImageGenerator() {
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleGenerate = async (prompt) => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch('https://api.imagify.ca/api/images/generate', {
        method: 'POST',
        headers: {
          'X-API-Key': process.env.REACT_APP_IMAGIFY_API_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ prompt })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error);
      }

      const data = await response.json();
      setImageUrl(data.image.url);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={() => handleGenerate('A beautiful landscape')}>
        Generate Image
      </button>
      {loading && <p>Generating...</p>}
      {error && <p>Error: {error}</p>}
      {imageUrl && <img src={imageUrl} alt="Generated" />}
    </div>
  );
}

Step 6: Best Practices

1. Store API Keys Securely

Never hardcode API keys. Use environment variables:

# .env file
IMAGIFY_API_KEY=your_api_key_here

2. Implement Rate Limiting

Respect rate limits and implement client-side throttling:

let lastRequestTime = 0;
const MIN_REQUEST_INTERVAL = 2000; // 2 seconds

async function generateImageWithThrottle(prompt) {
  const now = Date.now();
  const timeSinceLastRequest = now - lastRequestTime;
  
  if (timeSinceLastRequest < MIN_REQUEST_INTERVAL) {
    await new Promise(resolve => 
      setTimeout(resolve, MIN_REQUEST_INTERVAL - timeSinceLastRequest)
    );
  }
  
  lastRequestTime = Date.now();
  return await generateImage(prompt);
}

3. Cache Results

Cache generated images to avoid regenerating the same content:

const imageCache = new Map();

async function generateImageWithCache(prompt) {
  if (imageCache.has(prompt)) {
    return imageCache.get(prompt);
  }
  
  const imageUrl = await generateImage(prompt);
  imageCache.set(prompt, imageUrl);
  return imageUrl;
}

4. Show Loading States

Always provide user feedback during image generation:

function ImageGenerator() {
  const [loading, setLoading] = useState(false);
  
  const handleGenerate = async () => {
    setLoading(true);
    try {
      // Generate image
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div>
      {loading && <Spinner />}
      {/* Rest of UI */}
    </div>
  );
}

Common Integration Patterns

Batch Generation

Generate multiple images in sequence:

async function generateMultipleImages(prompts) {
  const images = [];
  for (const prompt of prompts) {
    try {
      const imageUrl = await generateImage(prompt);
      images.push({ prompt, url: imageUrl });
      // Add delay between requests
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      console.error(`Failed to generate image for: ${prompt}`, error);
    }
  }
  return images;
}

Background Generation

Generate images in the background and notify when complete:

async function generateImageInBackground(prompt, callback) {
  try {
    const imageUrl = await generateImage(prompt);
    callback(null, imageUrl);
  } catch (error) {
    callback(error, null);
  }
}

// Usage
generateImageInBackground('A beautiful sunset', (error, imageUrl) => {
  if (error) {
    console.error('Generation failed:', error);
  } else {
    console.log('Image ready:', imageUrl);
  }
});

Next Steps

Now that you've integrated the API, consider:

1. Building a UI: Create a user-friendly interface for image generation

2. Image History: Implement image history using the history endpoint

3. Credit Management: Add credit balance display and purchase flow

4. Error Recovery: Implement retry logic for failed requests

Conclusion

Integrating AI image generation into your application is straightforward with Imagify's API. Follow these steps, implement best practices, and you'll have AI-powered image generation working in no time.

Get started with free credits and begin building amazing features!

Ready to Start Generating Images?

Get started with free credits and begin creating amazing AI-generated images today.

Get Started Free