# Image Generation API Reference

{% hint style="info" %}
**Good to know:** A quick start guide can be good to help folks get up and running with your API in a few steps. Some people prefer diving in with the basics rather than meticulously reading every page of documentation!
{% endhint %}

## Get your API keys

Your `API` requests are authenticated using `API` keys. Any request that doesn't include an `API` key will return an `error`.

You can generate an `API` key from your user `dashboard` in [Miragic](https://miragic.ai/) website anytime.

<figure><img src="https://3797193121-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft2ubAKYPEaJXBQZaRNa5%2Fuploads%2FQRG37HdbiuNEPYckUX7g%2FScreenshot%202025-10-10%20084345.png?alt=media&#x26;token=9b926638-0508-4358-8eee-6a9913c50034" alt=""><figcaption></figcaption></figure>

## Authentication

All requests must include the `X-API-Key` header containing your assigned `API` key.&#x20;

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://backend.miragic.ai/api/v1/image/generate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "prompt=A beatiful sunset over the ocean" \
  -F "model=flux" \
  -F "width=2048" \
  -F "height=1024"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import fs from "fs";
import FormData from "form-data";
import fetch from "node-fetch";

const apiKey = "YOUR_API_KEY";
const baseUrl = "https://backend.miragic.ai";

async function image_gen() {
  const url = `${baseUrl}/api/v1/image/generate`;

  const formData = new FormData();
  formData.append("prompt", "A beatiful sunset over the ocean");
  formData.append("model", "flux");
  formData.append("width", "2048");
  formData.append("height", "1024");

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "X-API-Key": apiKey,
      ...formData.getHeaders(),
    },
    body: formData,
  });

  const result = await response.text();
  console.log(result);
}

image_gen();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

api_key = 'YOUR_API_KEY'   # ← Replace with your actual API key
base_url = 'https://backend.miragic.ai'

def image_gen():
    url = f'{base_url}/api/v1/image/generate'

    data = {
        'prompt': 'A beatiful sunset over the ocean',    # Any text available
        'model': 'flux',    # 'flux', 'turbo', 'gptimage', 'kontext'
        'width': 2048, # The valid value range is 256–2048 
        'height': 1024   # The valid value range is 256–2048
    }
    headers = {'X-API-Key': api_key}
    response = requests.request("POST", url, headers=headers, data=data)
    print(response.text)

if __name__ == '__main__':
    image_gen()
```

{% endtab %}
{% endtabs %}

## How To Create Image Generation Task

<mark style="background-color:green;">POST</mark>   `/api/v1/image/generate`

This `API` starts the `Image Generation` process by creating a task that generates a stunning art images.

{% hint style="info" %}
Processing Information

* Tasks are processed asynchronously in the background
* Progress can be monitored using the `Get Task Status API`
* The final result will be a high-quality image
  {% endhint %}

### Request

<table><thead><tr><th width="121">Parameter</th><th width="99">Type</th><th width="108">Required</th><th>Description</th></tr></thead><tbody><tr><td>prompt</td><td>String</td><td>Yes</td><td>Input text to demonstrate output image.</td></tr><tr><td>model</td><td>String</td><td>Yes</td><td>AI model option for image generation. The values can be <code>flux</code>, <code>turbo</code>, <code>gptimage</code>, and <code>kontext</code>.</td></tr><tr><td>width</td><td>Number</td><td>Yes</td><td>The valid value range is <code>256</code>-<code>2048</code></td></tr><tr><td>height</td><td>Number</td><td>Yes</td><td>The valid value range is <code>256</code>-<code>2048</code>.</td></tr><tr><td>image_url</td><td>String</td><td>Optional</td><td>This value represents the <code>URL</code> of the input image for <code>image-to-image</code> tasks. It is only available when the model is set to <code>kontext</code>.</td></tr></tbody></table>

<mark style="color:green;">**Request Example (Text-To-Image)**</mark>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://backend.miragic.ai/api/v1/image/generate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "prompt=A beatiful sunset over the ocean" \
  -F "model=flux" \
  -F "width=2048" \
  -F "height=1024"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import fs from "fs";
import FormData from "form-data";
import fetch from "node-fetch";

const apiKey = "YOUR_API_KEY";
const baseUrl = "https://backend.miragic.ai";

async function image_gen() {
  const url = `${baseUrl}/api/v1/image/generate`;

  const formData = new FormData();
  formData.append("prompt", "A beatiful sunset over the ocean");
  formData.append("model", "flux");
  formData.append("width", "2048");
  formData.append("height", "1024");

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "X-API-Key": apiKey,
      ...formData.getHeaders(),
    },
    body: formData,
  });

  const result = await response.text();
  console.log(result);
}

image_gen();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

api_key = 'YOUR_API_KEY'   # ← Replace with your actual API key
base_url = 'https://backend.miragic.ai'

def image_gen():
    url = f'{base_url}/api/v1/image/generate'

    data = {
        'prompt': 'A beatiful sunset over the ocean',    # Any text available
        'model': 'flux',    # 'flux', 'turbo', 'gptimage', 'kontext'
        'width': 2048, # The valid value range is 256–2048 
        'height': 1024   # The valid value range is 256–2048
    }
    headers = {'X-API-Key': api_key}
    response = requests.request("POST", url, headers=headers, data=data)
    print(response.text)

if __name__ == '__main__':
    image_gen()
```

{% endtab %}
{% endtabs %}

<mark style="color:green;">**Request Example (Image-To-Image)**</mark>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://backend.miragic.ai/api/v1/image/generate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "prompt=A beatiful sunset over the ocean" \
  -F "model=flux" \
  -F "width=2048" \
  -F "height=1024" \
  -F "image_url=https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import fs from "fs";
import FormData from "form-data";
import fetch from "node-fetch";

const apiKey = "YOUR_API_KEY";
const baseUrl = "https://backend.miragic.ai";

async function image_gen() {
  const url = `${baseUrl}/api/v1/image/generate`;

  const formData = new FormData();
  formData.append("prompt", "A beatiful sunset over the ocean");
  formData.append("model", "flux");
  formData.append("width", "2048");
  formData.append("height", "1024");
  formData.append("image_url", "https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg");

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "X-API-Key": apiKey,
      ...formData.getHeaders(),
    },
    body: formData,
  });

  const result = await response.text();
  console.log(result);
}

image_gen();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

api_key = 'YOUR_API_KEY'   # ← Replace with your actual API key
base_url = 'https://backend.miragic.ai'

def image_gen():
    url = f'{base_url}/api/v1/image/generate'

    data = {
        'prompt': 'A beatiful sunset over the ocean',    # Any text available
        'model': 'flux',    # 'flux', 'turbo', 'gptimage', 'kontext'
        'width': 2048, # The valid value range is 256–2048 
        'height': 1024,   # The valid value range is 256–2048
        'image_url': 'https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg'
    }
    headers = {'X-API-Key': api_key}
    response = requests.request("POST", url, headers=headers, data=data)
    print(response.text)

if __name__ == '__main__':
    image_gen()
```

{% endtab %}
{% endtabs %}

<mark style="color:green;">**Response**</mark>

```bash
{"success":true,"data":{"jobId":"56ba3768-2195-464c-98cd-e9dc535c2258","status":"PENDING"},"message":"Image generation job created successfully"}
```

**Response Field**

<table><thead><tr><th width="96">Field</th><th width="83">Type</th><th>Description</th></tr></thead><tbody><tr><td>jobId</td><td>String</td><td>A unique identifier used to track task status and retrieve results.</td></tr><tr><td>status</td><td>String</td><td>The initial status will be <code>PENDING</code>. Use the <code>Get Task Status API</code> to track progress.</td></tr><tr><td>message</td><td>String</td><td>To describe task status</td></tr><tr><td>success</td><td>Logic</td><td><code>true</code> or <code>false</code> to indicate whether task is successful or not.</td></tr></tbody></table>

## How To Get Task Status

<mark style="background-color:green;">GET</mark>   `/api/v1/image/jobs/:jobId`

This `API` lets you check the status of a image generation task and retrieve the final result. Because the image generation process runs asynchronously, you’ll need to poll this endpoint until the task is finished.

### Task Status:

<table><thead><tr><th width="105">Status</th><th width="202">Description</th><th width="82">Progress</th><th>Next Action</th></tr></thead><tbody><tr><td><code>PENDING</code></td><td>Task is currently being processed.</td><td><code>0</code>~<code>99</code>%</td><td>Continue polling</td></tr><tr><td><code>COMPLETED</code></td><td>Task has finished successfully.</td><td><code>100</code>%</td><td>Download result using download_signed_url</td></tr><tr><td><code>FAILED</code></td><td>Task processing failed.</td><td>N/A</td><td>Check error details and retry if needed</td></tr></tbody></table>

{% hint style="info" %} <mark style="color:green;">**Progress Tracking:**</mark>

* The `progress` field indicates the percentage of task completion (`0`-`100`)
* Progress updates are available in real-time during the `PENDING` state
* Progress increases as the AI processes different stages of the try-on task
  {% endhint %}

{% hint style="info" %}
**Polling Guidelines:**

* Start polling immediately after creating the task
* Implement exponential backoff to avoid rate limiting
* The download\_signed\_url is temporary and should be used promptly
* Consider implementing a timeout after extended polling
  {% endhint %}

### Request:

<mark style="color:blue;">**URL Parameters**</mark>

<table><thead><tr><th width="123">Parameter</th><th width="85">Type</th><th width="105">Required</th><th>Description</th></tr></thead><tbody><tr><td>JobId</td><td>String</td><td>Yes</td><td>This value indicates task <code>ID</code> assigned by requesting <code>Image Generation</code> process <code>API</code></td></tr></tbody></table>

<mark style="color:blue;">**Request Example**</mark>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET https://backend.miragic.ai/api/v1/image/jobs/25331fb2-d0b0-44f6fcc85e3e \
  -H "X-API-Key: YOUR_API_KEY"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const fetch = require("node-fetch"); // for Node.js

const apiKey = "YOUR_API_KEY";
const jobId = "25331fb2-d0b0-44f6fcc85e3e";
const url = `https://backend.miragic.ai/api/v1/image/jobs/${jobId}`;

const options = {
  method: "GET",
  headers: {
    "X-API-Key": apiKey
  }
};

fetch(url, options)
  .then(response => response.json())
  .then(data => {
    console.log("Response:", data);
  })
  .catch(error => {
    console.error("Error:", error);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_key = "YOUR_API_KEY"
job_id = "25331fb2-d0b0-44f6fcc85e3e"
url = f"https://backend.miragic.ai/api/v1/image/jobs/{job_id}"

headers = {
    "X-API-Key": api_key
}

response = requests.get(url, headers=headers)

# Print status code and response JSON
print("Status Code:", response.status_code)
print("Response:", response.json())
```

{% endtab %}
{% endtabs %}

<mark style="color:blue;">**Response Example**</mark>

#### Completed Status (200):

```bash
{'success': True, 'data': {'id': '56ba3768-2195-464c-98cd-e9dc535c2258', 'userId': 'eebf31b5-7bec-445e-8b99-51c0311a389d', 'prompt': 'A beautiful sunset over the ocean', 'parameters': {'safe': 'false', 'seed': '', 'model': 'flux', 'width': '2048', 'height': '1024', 'nologo': 'true', 'prompt': 'A beautiful sunset over the ocean', 'enhance': 'false', 'private': 'false', 'image_url': '', 'uploaded_image_path': ''}, 'status': 'COMPLETED', 'imageUrl': 'https://backend.miragic.ai/uploads/image-generation/processed/eebf31b5-7bec-445e-8b99-51c0311a389d/1ce867db-a8ca-4cc2-89dc-1e1b67c3fc90.jpg', 'processedImageUrl': 'https://backend.miragic.ai/uploads/image-generation/processed/eebf31b5-7bec-445e-8b99-51c0311a389d/1ce867db-a8ca-4cc2-89dc-1e1b67c3fc90.jpg', 'storagePath': None, 'publicId': None, 'metadata': {'apiResponse': {'link': 'https://www.dropbox.com/scl/fi/kwmrnqzb5scb8acp9t6g5/c8ac746a-c46b-404f-b9de-f27887e05e03.jpg?rlkey=5iqqfh4yzfg49kq8hbih5sbd5&raw=1', 'success': True}, 'has_input_image': False, 'processingTimeMs': 4827, 'uploaded_image_path': None}, 'resolution': None, 'errorMessage': None, 'creditsUsed': 1, 'createdAt': '2025-11-05T13:52:00.801Z', 'updatedAt': '2025-11-05T13:52:05.629Z'}}
```

<mark style="color:blue;">**Response Fields**</mark>

<table><thead><tr><th width="176">Field</th><th width="103">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>String</td><td>Unique identifier of the task</td></tr><tr><td>status</td><td>String</td><td>Current status of the task (<code>PENDING</code>/<code>COMPLETED</code>/<code>FAILED</code>)</td></tr><tr><td>userId</td><td>String</td><td>Unique identifier of the user</td></tr><tr><td>processedImageUrl</td><td>String</td><td><code>URL</code> to result image</td></tr><tr><td>createdAt</td><td>Number</td><td>Unix timestamp when processing is created</td></tr><tr><td>errorMessage</td><td>String</td><td>Error message</td></tr></tbody></table>

## Full Code Example

The following code lines are quick example to use our `API` in multiple languages.

<mark style="color:green;">**Case 1: Text-To-Image**</mark>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://backend.miragic.ai/api/v1/image/generate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "prompt=A beatiful sunset over the ocean" \
  -F "model=flux" \
  -F "width=2048" \
  -F "height=1024"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import axios from "axios";
import fs from "fs";
import FormData from "form-data";

const apiKey = "YOUR_API_KEY";
const baseUrl = "https://devapi.miragic.ai";

async function image_gen() {
  const url = `${baseUrl}/api/v1/image/generate`;

  // Form data with your settings
  const form = new FormData();
  formData.append("prompt", "A beatiful sunset over the ocean");
  formData.append("model", "flux");
  formData.append("width", "2048");
  formData.append("height", "1024");

  const headers = {
    "X-API-Key": apiKey,
    ...form.getHeaders(),
  };

  try {
    // Step 1: Create job
    const response = await axios.post(url, form, { headers });
    console.log(response.data);

    if (response.data.success) {
      const jobId = response.data.data.jobId;
      console.log(`Job ID: ${jobId}`);

      // Step 2: Poll for results
      let status = "PENDING";
      while (status !== "COMPLETED" && status !== "FAILED") {
        await new Promise((r) => setTimeout(r, 2000)); // wait 2 sec
        const result = await axios.get(`${baseUrl}/api/v1/image/jobs/${jobId}`, {
          headers: { "X-API-Key": apiKey },
        });

        status = result.data.data.status;

        if (status === "COMPLETED") {
          console.log("Result:", result.data);
          break;
        } else if (status === "FAILED") {
          console.log("Job failed:", result.data);
          break;
        } else {
          console.log(`Current status: ${status}...`);
        }
      }
    } else {
      console.log("Error:", response.data);
    }
  } catch (error) {
    console.error("Request failed:", error.response?.data || error.message);
  }
}

image_gen();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

api_key = 'YOUR_API_KEY'   # ← Replace with your actual API key
base_url = 'https://backend.miragic.ai'

def image_gen():
    url = f'{base_url}/api/v1/image/generate'
    
    data = {
        'prompt': 'A beatiful sunset over the ocean',    # Any text available
        'model': 'flux',    # 'flux', 'turbo', 'gptimage', 'kontext'
        'width': 2048, # The valid value range is 256–2048 
        'height': 1024   # The valid value range is 256–2048
    }

    headers = {'X-API-Key': api_key}
    response = requests.request("POST", url, headers=headers, data=data)
    print(response.text)
    
    if response.json()['success']:
        job_id = response.json()['data']['jobId']
        print(f'Job ID: {job_id}')
        
        # Poll for results
        while True:
            result = requests.get(
                f'{base_url}/api/v1/image/jobs/{job_id}',
                headers=headers
            )
            
            if result.json()['data']['status'] == 'COMPLETED':
                print('Result:', result.json())
                break
            elif result.json()['data']['status'] == 'FAILED':
                print('Job failed:', result.json())
                break
            
            time.sleep(2)
    else:
        print('Error:', response.json())

if __name__ == '__main__':
    image_gen()
```

{% endtab %}
{% endtabs %}

<mark style="color:green;">**Case 2: Image-To-Image**</mark>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://backend.miragic.ai/api/v1/image/generate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "prompt=A beatiful sunset over the ocean" \
  -F "model=flux" \
  -F "width=2048" \
  -F "height=1024" \
  -F "image_url=https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import axios from "axios";
import fs from "fs";
import FormData from "form-data";

const apiKey = "YOUR_API_KEY";
const baseUrl = "https://devapi.miragic.ai";

async function image_gen() {
  const url = `${baseUrl}/api/v1/image/generate`;

  // Form data with your settings
  const form = new FormData();
  formData.append("prompt", "A beatiful sunset over the ocean");
  formData.append("model", "flux");
  formData.append("width", "2048");
  formData.append("height", "1024");
  formData.append("image_url", "https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg");

  const headers = {
    "X-API-Key": apiKey,
    ...form.getHeaders(),
  };

  try {
    // Step 1: Create job
    const response = await axios.post(url, form, { headers });
    console.log(response.data);

    if (response.data.success) {
      const jobId = response.data.data.jobId;
      console.log(`Job ID: ${jobId}`);

      // Step 2: Poll for results
      let status = "PENDING";
      while (status !== "COMPLETED" && status !== "FAILED") {
        await new Promise((r) => setTimeout(r, 2000)); // wait 2 sec
        const result = await axios.get(`${baseUrl}/api/v1/image/jobs/${jobId}`, {
          headers: { "X-API-Key": apiKey },
        });

        status = result.data.data.status;

        if (status === "COMPLETED") {
          console.log("Result:", result.data);
          break;
        } else if (status === "FAILED") {
          console.log("Job failed:", result.data);
          break;
        } else {
          console.log(`Current status: ${status}...`);
        }
      }
    } else {
      console.log("Error:", response.data);
    }
  } catch (error) {
    console.error("Request failed:", error.response?.data || error.message);
  }
}

image_gen();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

api_key = 'YOUR_API_KEY'   # ← Replace with your actual API key
base_url = 'https://backend.miragic.ai'

def image_gen():
    url = f'{base_url}/api/v1/image/generate'

    data = {
        'prompt': 'A beatiful sunset over the ocean',    # Any text available
        'model': 'flux',    # 'flux', 'turbo', 'gptimage', 'kontext'
        'width': 2048, # The valid value range is 256–2048 
        'height': 1024,   # The valid value range is 256–2048
        'image_url': 'https://images.tech.co/wp-content/uploads/2023/11/21202640/AI-generated-landscape-708x400.jpg'
    }

    headers = {'X-API-Key': api_key}
    response = requests.request("POST", url, headers=headers, data=data)
    print(response.text)
    
    if response.json()['success']:
        job_id = response.json()['data']['jobId']
        print(f'Job ID: {job_id}')
        
        # Poll for results
        while True:
            result = requests.get(
                f'{base_url}/api/v1/image/jobs/{job_id}',
                headers=headers
            )
            if result.json()['data']['status'] == 'COMPLETED':
                print('Result:', result.json())
                break
            elif result.json()['data']['status'] == 'FAILED':
                print('Job failed:', result.json())
                break
            time.sleep(2)
    else:
        print('Error:', response.json())

if __name__ == '__main__':
    image_gen()
```

{% endtab %}
{% endtabs %}
