# HDR Brackets

In this guide we will be walking you through how to enhance your first HDR image, you will:

1. Learn how to register the fact you want to upload 2 or more brackets for an HDR image with Autoenhance
2. Upload your image file for each bracket to Autoenhance using the provided endpoint received after registering your image
3. Tell Autoenhance you have finished uploading your brackets and you are ready for it to start merging them.
4. Checking the status of the order
5. Downloading the final enhanced HDR image

This guide assumes the following:

* You already have an API key, if you don't have one please see our [guide here.](https://docs.autoenhance.ai/getting-started/obtaining-an-api-key)
* That you have already uploaded a single bracket, if you haven't we reccomend you follow our [guide here](https://docs.autoenhance.ai/getting-started/quickstart/single-bracket)

### 1. Creating an Order

Before we can upload some brackets we need to create an order for them live so that Autoenhance understands that they are related to each other. To do this we issue a `POST` request to the `/orders` endpoint.

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

```javascript
const createOrder = async (apiKey) => {
    const createOrderResponse = await fetch(
      "https://api.autoenhance.ai/v3/orders/",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
        }
      }
    );

    return { order_id } = await createOrderResponse.json();
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def create_order(api_key):
    create_order_url = "https://api.autoenhance.ai/v3/orders/"
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key,
    }
    
    create_order_response = requests.post(create_order_url, headers=headers)
    
    if create_order_response.status_code != 200:
        create_order_response.raise_for_status()

    return create_order_response.json['order_id']
```

{% endtab %}

{% tab title="PHP" %}

```php
function create_order($api_key) {
    $create_order_url = "https://api.autoenhance.ai/v3/orders/";

    $create_order_options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n" .
                         "x-api-key: $api_key",
            'method'  => 'POST'
        ),
    );

    $create_order_context  = stream_context_create($create_order_options);
    $create_order_result = file_get_contents($create_order_url, false, $create_order_context);

    if ($create_order_result === FALSE) {
        echo 'Error creating order';
        return;
    }

    $create_order_response = json_decode($create_order_result, true);
    return $create_image_response['order_id'];
}
```

{% endtab %}

{% tab title="cURL" %}

```javascript
curl -X POST \
  https://api.autoenhance.ai/v3/orders/ \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY'
```

{% endtab %}
{% endtabs %}

### 2. Uploading the brackets

Now we need to register and upload the file for each bracket, to do this we create a `POST` request to the dedicated `/brackets` endpoint and provide the order\_id we got from the orders endpoint`.` This is so that Autoenhance knows that these brackets belong together and are eligible to be merged together.

{% hint style="info" %}
You can provide the name of each bracket in the name property, the final image takes the name from the first bracket and this can be a useful way to cross-reference which brackets you have uploaded<br>

Customers who don't specify the API version header and use an older account defaulting to older API version will receive `s3PutObjectUrl` instead of `upload_url` in the response from create bracket response!
{% endhint %}

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

```javascript
const uploadBracket = async (orderId, apiKey, file) =>
    const createBracketResponse = await fetch(
      "https://api.autoenhance.ai/v3/brackets/",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
        },
        body: JSON.stringify({
          order_id: orderId, // order_id needs to be specified
          name: file.name
        }),
      }
    );

    const { upload_url } = await createBracketResponse.json();
    
    if(upload_url){
      const uploadImageResponse = await fetch(upload_url, {
        method: "PUT",
        headers: {
          "Content-Type": 'application/octet-stream',
          "x-api-key": apiKey,
        },
        body: file,
      });
      
      if(uploadImageResponse.ok){
        console.log('Image successfully uploaded')
      } else {
        console.log('Error uploading image');
      }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

def upload_bracket(order_id, api_key, file_path):
    create_bracket_url = "https://api.autoenhance.ai/v3/brackets/"
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key,
    }
    payload = {
        "order_id": order_id, # order_id needs to be specified
        "name": file_path.split('/')[-1
    }
    
    create_bracket_response = requests.post(create_bracket_url, headers=headers, data=json.dumps(payload))
    
    if create_bracket_response.status_code != 200:
        create_bracket_response.raise_for_status()

    create_bracket_data = create_bracket_response.json()
    upload_url = create_bracket_data.get('upload_url')
    
    if upload_url:
        with open(file_path, 'rb') as file_data:
            upload_bracket_headers = {
                "Content-Type": 'application/octet-stream',
                "x-api-key": api_key,
            }
            upload_bracket_response = requests.put(upload_url, headers=upload_bracket_headers, data=file_data)
            
            return upload_bracket_response
    else:
        raise ValueError("s3PutObjectUrl not found in the response")
```

{% endtab %}

{% tab title="PHP" %}

```php
function upload_bracket($order_id, $api_key, $file) {
    $create_bracket_url = "https://api.autoenhance.ai/v3/brackets/";

    $create_bracket_data = array(
        "order_id" => $order_id,
        "name" => $file['name']
    );

    $create_bracket_options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n" .
                         "x-api-key: $api_key",
            'method'  => 'POST',
            'content' => json_encode($create_bracket_data),
        ),
    );

    $create_bracket_context  = stream_context_create($create_bracket_options);
    $create_bracket_result = file_get_contents($create_bracket_url, false, $create_bracket_context);

    if ($create_bracket_result === FALSE) {
        echo 'Error creating image';
        return;
    }

    $create_bracket_response = json_decode($create_bracket_result, true);
    $upload_url = $create_bracket_response['upload_url'];

    if ($upload_url) {
        $upload_image_options = array(
            'http' => array(
                'header'  => "Content-Type: application/octet-stream\r\n" .
                             "x-api-key: $api_key",
                'method'  => 'PUT',
                'content' => file_get_contents($file['tmp_name']),
            ),
        );

        $upload_image_context  = stream_context_create($upload_image_options);
        $upload_image_result = file_get_contents($upload_url, false, $upload_image_context);

        if ($upload_image_result === FALSE) {
            echo 'Error uploading image';
            return;
        }

        echo 'Image successfully uploaded';
    }
}
```

{% endtab %}

{% tab title="cURL" %}

```
Create image

curl -X POST \
  https://api.autoenhance.ai/v3/brackets/ \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "order_id": "YOUR_ORDER_ID",
        "name": "your-image-name.jpg",
      }'

Upload Image
Replace UPLOAD_URL with the value of s3PutObjectUrl received from the previous response

curl -X PUT \
  UPLOAD_URL \
  -H 'Content-Type: application/octet-stream' \
  -H 'x-api-key: YOUR_API_KEY' \
  --data-binary @path/to/your/image.jpg
```

{% endtab %}
{% endtabs %}

### 2. Grouping and enhancing your brackets

Once you have uploaded all of your brackets, you are now ready to request Autoenhance start grouping them into images and then enhancing them.

There are three options depending on your use case.

{% tabs %}
{% tab title="Visual Grouping" %}
By default when you call the `/orders/<order_id>/process` endpoint, Autoenhance will analyse the metadata and visual similarity of your brackets. They will be automatically grouped together and returned as a single HDR image.

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

```javascript
const uploadAllBrackets = async (apiKey, files, orderId) => {  
  const promises = files.map(file => uploadBracket(orderId, apiKey, file));
  
  await Promise.all(promises);
  const preferences = {
    ai_version: '5.x'
  };
  
  const mergeResponse = await fetch(
    `https://api.autoenhance.ai/v3/orders/${orderId}/process`,
    {
      method: "POST",
      headers: {
        "x-api-key": apiKey,
      }
      body: preferences
    }
  );
  
  // This is an URL to our web application where you can
  // take a look at your order, you don't need to return it.
  return `https://app.autoenhance.ai/orders/${orderId}`
};

const apiKey = YOUR_API_KEY;
const files = [File, File, File] // Array of Files or Blobs
const orderId = "YOUR_UNIQUE_ORDER_ID" // Ideally generated with uuidv4

uploadAllBrackets(apiKey, files, orderId)
```

{% endtab %}

{% tab title="Python" %}

```python
def upload_all_brackets(api_key, files, order_id):
    for file in files:
        upload_bracket(order_id, api_key, file)

    merge_url = f"https://api.autoenhance.ai/v3/orders/{order_id}/process"
    merge_headers = {"x-api-key": api_key}
    prefrences = {"ai_version: "5.x"}
    merge_response = requests.post(merge_url, headers=merge_headers, json=prefrences)
    if merge_response.status_code != 200:
        raise Exception(f"Failed to merge order: {merge_response.text}")
  
    #This is an URL to our web application where you can
    #take a look at your order, you don't need to return it.
    return f"https://app.autoenhance.ai/orders/{order_id}"

api_key = "YOUR_API_KEY"
files = [open('file1.jpg', 'rb'), open('file2.jpg', 'rb'), open('file3.jpg', 'rb')]  # List of file objects
order_id = "YOUR_UNIQUE_ORDER_ID"  # Ideally generated with uuid.uuid4()

order_url = upload_all_brackets(api_key, files, order_id)

# Close the files after uploading
for file in files:
    file.close()

print(order_url)
```

{% endtab %}

{% tab title="PHP" %}

```php
function upload_all_brackets($api_key, $files, $order_id) {
    $promises = array_map(function($file) use ($order_id, $api_key) {
        return upload_bracket($order_id, $api_key, $file);
    }, $files);

    $merge_url = "https://api.autoenhance.ai/v3/orders/$order_id/process";

    $preferences = [
        "ai_version" => "5.x"
    ];

    $merge_options = array(
        'http' => array(
            'header'  => "x-api-key: $api_key",
            'method'  => 'POST',
            'content' => json_encode($preferences),
        ),
    );

    $merge_context  = stream_context_create($merge_options);
    $merge_result = file_get_contents($merge_url, false, $merge_context);

    if ($merge_result === FALSE) {
        return 'Error merging brackets';
    }

    // Return the URL to the web application
    return "https://app.autoenhance.ai/orders/$order_id";
}

$api_key = "YOUR_API_KEY";
$files = [/* Array of Files or Blobs */];
$order_id = "YOUR_UNIQUE_ORDER_ID";

upload_all_brackets($api_key, $files, $order_id);
```

{% endtab %}

{% tab title="cURL" %}

```javascript
Upload each bracket

for file in file1 file2 file3; do
    # Replace file1, file2, file3 with the actual paths to your files
    curl -X POST \
      https://api.autoenhance.ai/v3/brackets/ \
      -H 'Content-Type: application/json' \
      -H 'x-api-key: YOUR_API_KEY' \
      -d '{
            "order_id": "YOUR_ORDER_ID",
            "name": "your-image-name.jpg"
          }'
done

Merge brackets

curl -X POST \
  https://api.autoenhance.ai/v3/orders/YOUR_ORDER_ID/process \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{"ai_version": "5.x" }'
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="Fixes group sizes" %}
In cases where you already know each time how many brackets you shot you can provide the `/orders/<order_id>/process` endpoint the `number_of_brackets_per_image` field with a number - in this case Autoenhance will sort your brackets by the time they were shot using their metadata and group your brackets based on this i.e if you set this to 3 then every 3 brackets will be grouped into one image

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

```javascript
const uploadAllBrackets = async (apiKey, files, orderId) => {  
  const promises = files.map(file => uploadBracket(orderId, apiKey, file));
  
  await Promise.all(promises);
  
  const mergeResponse = await fetch(
    `https://api.autoenhance.ai/v3/orders/${orderId}/process`,
    {
      method: "POST",
      headers: {
        "x-api-key": apiKey,
      },
      body: {
        number_of_brackets_per_image: 5
      }
    }
  );
  
  // This is an URL to our web application where you can
  // take a look at your order, you don't need to return it.
  return `https://app.autoenhance.ai/orders/${orderId}`
};

const apiKey = YOUR_API_KEY;
const files = [File, File, File] // Array of Files or Blobs
const orderId = "YOUR_UNIQUE_ORDER_ID" // Ideally generated with uuidv4

uploadAllBrackets(apiKey, files, orderId)
```

{% endtab %}

{% tab title="Python" %}

```python
def upload_all_brackets(api_key, files, order_id):
    for file in files:
        upload_bracket(order_id, api_key, file)

    merge_url = f"https://api.autoenhance.ai/v3/orders/{order_id}/process"
    merge_headers = {"x-api-key": api_key}
    merge_response = requests.post(merge_url, headers=merge_headers, json={
       "number_of_brackets_per_image": 5
    })
    if merge_response.status_code != 200:
        raise Exception(f"Failed to merge order: {merge_response.text}")
  
    #This is an URL to our web application where you can
    #take a look at your order, you don't need to return it.
    return f"https://app.autoenhance.ai/orders/{order_id}"

api_key = "YOUR_API_KEY"
files = [open('file1.jpg', 'rb'), open('file2.jpg', 'rb'), open('file3.jpg', 'rb')]  # List of file objects
order_id = "YOUR_UNIQUE_ORDER_ID"  # Ideally generated with uuid.uuid4()

order_url = upload_all_brackets(api_key, files, order_id)

# Close the files after uploading
for file in files:
    file.close()

print(order_url)
```

{% endtab %}

{% tab title="PHP" %}

```php
function upload_all_brackets($api_key, $files, $order_id) {
    $promises = array_map(function($file) use ($order_id, $api_key) {
        return upload_bracket($order_id, $api_key, $file);
    }, $files);

    $merge_url = "https://api.autoenhance.ai/v3/orders/$order_id/process";

    $merge_options = array(
        'http' => array(
            'header'  => "x-api-key: $api_key",
            'method'  => 'POST',
            'content' => json_encode(array('number_of_brackets_per_image' => 5))
            )
        ),
    );

    $merge_context  = stream_context_create($merge_options);
    $merge_result = file_get_contents($merge_url, false, $merge_context);

    if ($merge_result === FALSE) {
        return 'Error merging brackets';
    }

    // Return the URL to the web application
    return "https://app.autoenhance.ai/orders/$order_id";
}

$api_key = "YOUR_API_KEY";
$files = [/* Array of Files or Blobs */];
$order_id = "YOUR_UNIQUE_ORDER_ID";

upload_all_brackets($api_key, $files, $order_id);
```

{% endtab %}

{% tab title="cURL" %}

```bash
Upload each bracket

for file in file1 file2 file3; do
    # Replace file1, file2, file3 with the actual paths to your files
    curl -X POST \
      https://api.autoenhance.ai/v3/brackets/ \
      -H 'Content-Type: application/json' \
      -H 'x-api-key: YOUR_API_KEY' \
      -d '{
            "order_id": "YOUR_ORDER_ID",
            "name": "your-image-name.jpg"
          }'
done

Merge brackets

curl -X POST \
  https://api.autoenhance.ai/v3/orders/YOUR_ORDER_ID/process \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY'
  =d '{ "number_of_brackets_per_image": 5"}'
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="Manually grouped brackets" %}
In cases where you have already grouped your brackets, you can send these groups to Autoenhance by passing an "images" array , each item should be an object containing a "bracket\_ids" fields containing another array with the ID for each bracket you registered earlier.

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

```javascript
const uploadAllBrackets = async (apiKey, files, orderId) => {  
  const promises = files.map(file => uploadBracket(orderId, apiKey, file));
  
  const results = await Promise.all(promises);
  const bracketIds = results.map(result => result.bracket_id);
  
  const preferences = {
    ai_version: '5.x'
  }
  
  const mergeResponse = await fetch(
    `https://api.autoenhance.ai/v3/orders/${orderId}/process`,
    {
      method: "POST",
      headers: {
        "x-api-key": apiKey,
      },
      body: {
         images: [
           {
              {
                "bracket_ids": bracketIds
              }
           }
         ],
         ...preferences
      }
    }
  );
  
  // This is an URL to our web application where you can
  // take a look at your order, you don't need to return it.
  return `https://app.autoenhance.ai/orders/${orderId}`
};

const apiKey = YOUR_API_KEY;
const files = [File, File, File] // Array of Files or Blobs
const orderId = "YOUR_UNIQUE_ORDER_ID" // Ideally generated with uuidv4

uploadAllBrackets(apiKey, files, orderId)
```

{% endtab %}

{% tab title="Python" %}

```python
def upload_all_brackets(api_key, files, order_id):

    bracket_ids = []
    for file in files:
        bracket_ids.append(upload_bracket(order_id, api_key, file))

    merge_url = f"https://api.autoenhance.ai/v3/orders/{order_id}/process"
    merge_headers = {"x-api-key": api_key}
    merge_response = requests.post(merge_url, headers=merge_headers, json={
        "images": [
        {
            "bracket_ids": bracket_ids
        }
        ]
    })
    if merge_response.status_code != 200:
        raise Exception(f"Failed to merge order: {merge_response.text}")
  
    #This is an URL to our web application where you can
    #take a look at your order, you don't need to return it.
    return f"https://app.autoenhance.ai/orders/{order_id}"

api_key = "YOUR_API_KEY"
files = [open('file1.jpg', 'rb'), open('file2.jpg', 'rb'), open('file3.jpg', 'rb')]  # List of file objects
order_id = "YOUR_UNIQUE_ORDER_ID"  # Ideally generated with uuid.uuid4()

order_url = upload_all_brackets(api_key, files, order_id)

# Close the files after uploading
for file in files:
    file.close()

print(order_url)
```

{% endtab %}

{% tab title="PHP" %}

<pre class="language-php"><code class="lang-php">function upload_all_brackets($api_key, $files, $order_id) {
    $bracket_ids = [];

<strong>    foreach ($files as $file) {
</strong>        $response = upload_bracket($order_id, $api_key, $file);

        $data = json_decode($response, true);

        if (isset($data['bracket_id'])) {
            $bracket_ids[] = $data['bracket_id'];
        }
    }

    $merge_payload = json_encode([
        'images' => [
            [
                'bracket_ids' => $bracket_ids
            ]
        ]
    ]);

    $merge_url = "https://api.autoenhance.ai/v3/orders/$order_id/process";

    $merge_options = array(
        'http' => array(
            'header'  => "x-api-key: $api_key",
            'method'  => 'POST',
            'content' => $merge_payload,
        ),
    );

    $merge_context  = stream_context_create($merge_options);
    $merge_result = file_get_contents($merge_url, false, $merge_context);

    if ($merge_result === FALSE) {
        return 'Error merging brackets';
    }

    // Return the URL to the web application
    return "https://app.autoenhance.ai/orders/$order_id";
}

$api_key = "YOUR_API_KEY";
$files = [/* Array of Files or Blobs */];
$order_id = "YOUR_UNIQUE_ORDER_ID";

upload_all_brackets($api_key, $files, $order_id);
</code></pre>

{% endtab %}

{% tab title="cURL" %}

```bash
Upload each bracket

BRACKET_IDS=()
for file in file1 file2 file3; do
    # Replace file1, file2, file3 with the actual paths to your files
    RESPONSE=$(curl -X POST \
      https://api.autoenhance.ai/v3/brackets/ \
      -H 'Content-Type: application/json' \
      -H 'x-api-key: YOUR_API_KEY' \
      -d '{
            "order_id": "YOUR_ORDER_ID",
            "name": "your-image-name.jpg"
          }')
          
  # You will need "jq" installed
  BRACKET_ID=$(echo "$RESPONSE" | jq -r '.bracket_id')
  
  # Append to array if not null
  if [ "$BRACKET_ID" != "null" ]; then
    BRACKET_IDS+=("\"$BRACKET_ID\"")
  fi
  
done

Merge brackets

# Build JSON array from collected bracket IDs
BRACKET_IDS_JSON=$(printf ", %s" "${BRACKET_IDS[@]}")
BRACKET_IDS_JSON="[${BRACKET_IDS_JSON:2}]" # Remove leading comma

MERGE_PAYLOAD=$(cat <<EOF
{
  "images": [
    {
      "bracket_ids": $BRACKET_IDS_JSON
    }
  ]
}
EOF
)

echo "Sending merge request..."

curl -X POST \
  https://api.autoenhance.ai/v3/orders/$ORDER_ID/process \
  -H "Content-Type: application/json" \
  -H "x-api-key: $API_KEY" \
  -d "$MERGE_PAYLOAD"
```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

When calling the `/process` endpoint you can send all of the image preferences listed [here](https://docs.autoenhance.ai/images/basic-enhancements), these will be used when enhancing your images. If you do not provide these, we will apply default settings.

### 3. Checking the order status

Grouping brackets for each HDR image can take between 10 seconds to 5 minutes to complete depending on the number of brackets that need grouping.

We can check when this has finished by calling the `GET /order/<order_id>` endpoint and reading the `is_merging` and `is_processing` fields. Whilst the AI is still grouping the orders `is_merging` will be `true`, however if you want to display the progress of this grouping to customers then the `images` field will gradually be populated with images.

As each image is grouped the AI will automatically start enhancing them, you can check the status of each image individually using their `status` fields. Once all images have been enhanced the `is_processing` field for the order will change to `false` which can be used to stop showing any processing indicators to your end user.

You should always check your order status before downloading your images. In this case, we need to check whether the order has **falsy values** for **is\_merging** and **is\_processing** or not. You can start downloading all of your images once both of them are false.

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

```javascript
const orderId = "ID_OF_YOUR_ORDER";

const checkOrderStatus = async (orderId) => {
    const response = await fetch(`https://api.autoenhance.ai/orders/${orderId}`,{
        method: "GET"
    })
    
    const { is_merging, is_processing } = await response.json();
}
```

{% endtab %}

{% tab title="Python" %}

```python
order_id = "ID_OF_YOUR_ORDER";

def check_order_status(order_id):
    url = f"https://api.autoenhance.ai/v3/orders/{order_id}"
    
    response = requests.get(url)
    response_data = response.json()
    
    is_merging = response_data.get('is_merging')
    is_processing = response_data.get('is_processing')
    
    return is_merging, is_processing
```

{% endtab %}

{% tab title="PHP" %}

```php
function check_order_status($order_id) {
    $url = "https://api.autoenhance.ai/orders/$order_id";

    $options = array(
        'http' => array(
            'method'  => 'GET',
        ),
    );

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        return 'Error checking order status';
    }

    $response = json_decode($result, true);
    $is_merging = $response['is_merging'];
    $is_processing = $response['is_processing'];

    return array(
        'is_merging' => $is_merging,
        'is_processing' => $is_processing
    );
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl -X GET \
  https://api.autoenhance.ai/orders/ID_OF_YOUR_ORDER \
  -H 'Content-Type: application/json'
```

{% endtab %}
{% endtabs %}

### 4. Downloading image

Once our order has finished grouping and enhancing we can download the images as usual.

By default this endpoint will return a preview image you can show to your customers before they purchase the image. When they decide they want to download the image simply send `?preview=false` to purchase and download the full sized image from Autoenhance.\
\
During development you can test this workflow without using your credits by utilizing development mode, simply set the `x-dev-mode` to `true`. You can learn more about the development mode [here](https://docs.autoenhance.ai/images/downloading-images/enhanced#development-mode).

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

```javascript
const apiKey = "YOUR_API_KEY";
const imageId = "ID_OF_YOUR_IMAGE";

const checkImageStatus = async (imageId) => {
    const response = await fetch(`https://api.autoenhance.ai/v3/images/${imageId}`,{
         method: "GET"   
    })
    
    const {enhanced, error} = await response.json();
    
    return {
         enhanced:enhanced,
         error:error
    }
}

const downloadImage = async (imageId, apiKey) => {
     const imageStatus = await checkImageStatus(imageId);
     if(!imageStatus.error && imageStatus.enhanced){
        const response = await fetch(
        `https://api.autoenhance.ai/v3/images/${imageId}/enhanced`,
        { 
            method: "GET",
            headers: {
                "x-api-key": apiKey,
            },
        });
        const imageSource = await response.json()
    
        return imageSource
     }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_key = "YOUR_API_KEY"
image_id = "ID_OF_YOUR_IMAGE"

def check_image_status(image_id):
    response = requests.get(f"https://api.autoenhance.ai/v3/images/{image_id}")
    data = response.json()
    enhanced = data.get('enhanced')
    error = data.get('error')
    
    return {
        'enhanced': enhanced,
        'error': error
    }

def download_image(image_id, api_key):
    image_status = check_image_status(image_id)
    if not image_status['error'] and image_status['enhanced']:
        response = requests.get(
            f"https://api.autoenhance.ai/v3/images/{image_id}/enhanced",
            headers={
                "x-api-key": api_key,
            }
        )
        image_source = response.json()
        return image_source
```

{% endtab %}

{% tab title="PHP" %}

```php
$api_key = "YOUR_API_KEY";
$image_id = "ID_OF_YOUR_IMAGE";

function check_image_status($image_id) {
    $url = "https://api.autoenhance.ai/v3/images/" . $image_id;

    $options = array(
        'http' => array(
            'method'  => 'GET',
        ),
    );

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        return array(
            'enhanced' => false,
            'error' => 'Error checking image status'
        );
    }

    $response = json_decode($result, true);
    return array(
        'enhanced' => $response['enhanced'],
        'error' => $response['error']
    );
}

function download_image($image_id, $api_key) {
    $image_status = check_image_status($image_id);

    if (!$image_status['error'] && $image_status['enhanced']) {
        $url = "https://api.autoenhance.ai/v3/images/" . $image_id . "/enhanced";

        $options = array(
            'http' => array(
                'method'  => 'GET',
                'header'  => "x-api-key: $api_key"
            ),
        );

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        if ($result === FALSE) {
            return 'Error downloading enhanced image';
        }

        return json_decode($result, true);
    }

    return 'Image is not enhanced or an error occurred';
}
```

{% endtab %}

{% tab title="cURL" %}

```
Check image status

curl -X GET \
  https://api.autoenhance.ai/v3/images/ID_OF_YOUR_IMAGE \
  -H 'Content-Type: application/json'

Download image

curl -X GET \
  https://api.autoenhance.ai/v3/images/ID_OF_YOUR_IMAGE/enhanced \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
This example uses the least possible amount of properties in order to create an image. If you want to apply any kind of preferences to it, visit our [Image Settings](https://docs.autoenhance.ai/images/basic-enhancements) page to find out more about them. Once you are familiar with them, simply add them in the body of the POST request to our API.
{% endhint %}
