# Single Image

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

1. Learn how to register the fact you want to enhance an image with Autoenhance
2. Upload your image file to Autoenhance using the provided endpoint received after registering your image
3. Downloading the final enhanced image

This guide assumes you have 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)

### 1. Registering an image

So you have a single image you want to enhance using Autoenhance. Before we can upload anything we need to register our new image with Autoenhance, by passing a POST request to the `/images` endpoint.

During this process we provide the name and we indicate other editing settings we want to be applied to the image when it's enhanced but we won't cover that in this guide.

As part of this request Autoenhance will make a new record for this image and create space for us to upload our image including a unique endpoint which will be returned in the `upload_url` field

<details>

<summary>🔔 Note For <strong>Existing Customers</strong></summary>

{% hint style="info" %}
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!
{% endhint %}

</details>

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

```javascript
const apiKey = "YOUR_API_KEY";
const blob = Blob // Blob or File of your image

const createImage = async (apiKey, blob) => {
    const createImageResponse = await fetch(
      "https://api.autoenhance.ai/v3/images/",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
        },
        body: JSON.stringify({
          image_name: "your-image-name"
        }),
      }
    );

    const { upload_url, order_id, image_id } = await createImageResponse.json();
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

api_key = "YOUR_API_KEY"

def create_image(api_key, image_name, file):
    url = "https://api.autoenhance.ai/v3/images/"
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key,
    }
    payload = {
        "image_name": image_name
    }
    
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    
    if response.status_code == 200:
        data = response.json()
        s3_put_object_url = data.get('upload_url')
        order_id = data.get('order_id')
        image_id = data.get('image_id')
        return s3_put_object_url, order_id, image_id
    else:
        response.raise_for_status()

```

{% endtab %}

{% tab title="PHP" %}

```php
$api_key = "YOUR_API_KEY";

function create_image($api_key, $blob) {
    $url = "https://api.autoenhance.ai/v3/images/";
    $data = array(
        "image_name" => "your-image-name"
    );

    $options = array(
        'http' => array(
            'header'  => array(
                "Content-Type: application/json",
                "x-api-key: $apiKey"
            ),
            'method'  => 'POST',
            'content' => json_encode($data),
        ),
    );

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

    if ($result === FALSE) {
        die('Error creating image');
    }

    $response = json_decode($result, true);
    
    return $response['upload_url'];
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl -X POST \
  https://api.autoenhance.ai/v3/images/ \
  -H 'Content-Type: application/json' \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
        "image_name": "your-image-name"
      }'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Important note**\
You will see an **image\_id** and **order\_id** in the response. You can specify both of them yourself in the body of the request, but they both have to be unique. We're using [uuidv4](https://www.npmjs.com/package/uuid) in order to create unique identifiers for both orders and images.

\
If you want to group multiple images into the same order, you must use the exact same order\_id value for all of the created images. Learn more on the [Orders page](https://docs.autoenhance.ai/orders/managing-orders).
{% endhint %}

### 2. Uploading image

Now Autoenhance has registered our image and created a unique upload endpoint for us. We need to upload the file for the image we wish to be enhanced.

To do this we will perform a `PUT` request to the url contained provided at the `upload_url` field provided to us in Step 1, the body of this request should be the raw data of the file and the `Content-Type` header should always be `application/octet-stream`&#x20;

<details>

<summary>🔔 Note For <strong>Existing Customers</strong></summary>

{% hint style="info" %}
We previously required you to provide a  `content_type` property in the body of the request to create image, you must use a matching `Content-Type` header when sending the `PUT` request! A `403 Forbidden` error indicates the headers not matching.\
\
Eg. `content_type: "image/jpeg"` in the create image request body requires `"Content-Type": "image/jpeg"` in the headers of uploading image request.\
\
New customers can ignore this message.
{% endhint %}

</details>

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

<pre class="language-javascript"><code class="lang-javascript">const apiKey = "YOUR_API_KEY";
const blob = Blob // Blob or File of your image

<strong>const uploadImage = async (upload_url, blob, apikey) => {
</strong>  const uploadImageResponse = await fetch(uploadUrl, {
    method: "PUT",
    headers: {
      "Content-Type": "application/octet-stream",
      "x-api-key": apiKey,
    },
    body: blob,
  });
  
  if(uploadImageResponse.ok){
    console.log('Image successfully uploaded')
  } else {
    console.log('Error uploading image');
  }
};
</code></pre>

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_key = "YOUR_API_KEY"

def upload_image(upload_url, image_path, api_key, file):
    headers = {
        "Content-Type": "application/octet-stream",
        "x-api-key": api_key,
    }
    
    with open(image_path, 'rb') as image_file:
        image_data = image_file.read()
    
    response = requests.put(upload_url, headers=headers, data=image_data)
    
    return response
```

{% endtab %}

{% tab title="PHP" %}

```php
function upload_image($upload_url, $blob, $api_key) {
    $options = array(
        'http' => array(
            'header'  => array(
                "Content-Type: application/octet-stream",
                "x-api-key: $apiKey"
            ),
            'method'  => 'PUT',
            'content' => $blob["data"],
        ),
    );

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

    if ($result === FALSE) {
        echo 'Error uploading image';
    } else {
        echo 'Image successfully uploaded to S3';
    }
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
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 %}

### 3. Downloading image

Once successfully uploaded, your image will start being processed with our AI. To check it's current status we can use a GET request to the `/images/:image_id:/` using the `image_id` returned in the registration endpoint to get the current status.\
\
Once the status field returned is `"processed"`we can download the image using the `/images/:image_id:/enhanced` endpoint.\
\
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).  &#x20;

{% 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" %}

<pre class="language-bash"><code class="lang-bash"><strong>Checking the image status
</strong>
<strong>curl -X GET \
</strong>  https://api.autoenhance.ai/v3/images/ID_OF_YOUR_IMAGE \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY'
  
Downloading the 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'
</code></pre>

{% 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 %}
