Voltar ao blog
4 min readAPI In One Team

How to Build an AI Image Generator App — Developer Tutorial 2026

Step-by-step tutorial for building an AI image generator web app using the API in One unified API. Covers architecture, API integration, error handling, and deployment.

AI TutorialImage GenerationWeb DevelopmentAPI IntegrationDeveloper Guide
Este artigo está em inglês. Clique com o botão direito e selecione Traduzir.

Build your own AI image generator app in under an hour. Here’s the complete developer walkthrough using a unified AI API.

What You’ll Build

A web application that lets users type a text prompt and generate AI images. The app includes:

  • Text input for image generation prompts
  • AI model selection (Flux 2, Seedream, etc.)
  • Async task handling with status polling
  • Image display and download
  • Error handling and loading states

Architecture Overview

┌────────────┐     ┌────────────────┐     ┌──────────────────┐
│  Frontend   │────▶│  Your Backend   │────▶│  API in One      │
│  (React/Vue)│     │  (Node/Python)  │     │  (AI Models)     │
└────────────┘     └────────────────┘     └──────────────────┘

Key design decisions:

  • All API calls go through YOUR backend (never expose API keys to the frontend)
  • Use async generation with status polling (AI generation takes seconds)
  • Cache results to avoid duplicate API costs

Step 1: Get Your API Key

Sign up at apiin.one and generate an API key from your dashboard. Store it securely as an environment variable — never hardcode it.

API_KEY=aio_your_secret_key_here

Step 2: Implement the Generation Endpoint

Your backend receives the user’s prompt, forwards it to the AI API, and returns the task ID.

Node.js / Express Example

app.post('/api/generate', async (req, res) => {
  const { prompt, model } = req.body;

  const response = await fetch('https://apiin.one/api/v1/images/generations', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ model: model || 'flux-2', prompt })
  });

  const data = await response.json();
  res.json({ taskId: data.id, status: data.status });
});

Step 3: Implement Status Polling

AI image generation is asynchronous. Your frontend polls a status endpoint until the image is ready.

app.get('/api/status/:taskId', async (req, res) => {
  const response = await fetch(
    `https://apiin.one/api/v1/tasks/${req.params.taskId}`,
    {
      headers: { 'Authorization': `Bearer ${process.env.API_KEY}` }
    }
  );

  const data = await response.json();
  res.json({
    status: data.status,
    imageUrl: data.output?.image_url || null
  });
});

Frontend Polling Pattern

async function pollForResult(taskId) {
  const maxAttempts = 30;
  for (let i = 0; i < maxAttempts; i++) {
    const res = await fetch(`/api/status/${taskId}`);
    const data = await res.json();

    if (data.status === 'SUCCESS') return data.imageUrl;
    if (data.status === 'FAILED') throw new Error('Generation failed');

    await new Promise(r => setTimeout(r, 2000));
  }
  throw new Error('Timeout');
}

Step 4: Error Handling

Implement robust error handling for production use:

Error HTTP Code Action
Rate limited 429 Exponential backoff, retry
Insufficient credits 402 Show “top up credits” message
Content filtered 400 Show content policy message
Server error 500 Retry with backoff
Timeout - Show timeout message, offer retry

Step 5: Image Caching

Don’t regenerate the same image twice. Cache results using a simple hash-based approach:

const crypto = require('crypto');

function getPromptHash(prompt, model) {
  return crypto
    .createHash('sha256')
    .update(`${model}:${prompt}`)
    .digest('hex');
}

Store the hash → image URL mapping in your database or cache layer (Redis, etc.).

Step 6: Adding Multiple Models

The beauty of a unified API is that switching models requires only changing the model parameter:

// Flux 2 — Fast, high quality
{ model: 'flux-2', prompt: '...' }

// Seedream — ByteDance's model
{ model: 'seedream-5', prompt: '...' }

Your frontend can offer a model selector dropdown, and the backend code stays identical.

Production Considerations

Rate Limiting

Implement per-user rate limiting on your backend to prevent abuse and control API costs.

Content Moderation

Filter user prompts before sending to the API. Most AI APIs have built-in filters, but adding your own layer provides additional protection.

Cost Monitoring

Set up alerts for unusual spending patterns. Track per-user and per-model costs to optimize your pricing and usage.

Image Storage

Don’t rely on temporary API URLs. Download and store generated images in your own storage (S3, R2, etc.) for long-term access.

FAQ

How much does it cost to run an AI image generator app? With a unified API like API in One, image generation typically costs a few credits per image. At scale, costs depend on your usage patterns and caching effectiveness.

Can I let users choose between different AI models? Yes. With a unified API, adding model selection is trivial — just pass the model name in the request body. No additional integration work needed.

How do I handle long generation times? Use async polling (as shown above) with a loading indicator on the frontend. Most image generations complete in 5-15 seconds.

Should I use WebSockets instead of polling? For most apps, polling every 2 seconds is sufficient and simpler to implement. WebSockets make sense at high concurrency (100+ simultaneous users).