Developer API

Our services can be accessed through the powerful and easy-to-use Reducer API that covers all optimizing needs with just one method call.

If you are using WordPress, just install our WordPress plugin and you'll be up and running in seconds, without any implementation effort.

We also offer a PHP client library that features quick configuration and an easy fluent syntax for accessing our services thus greatly reducing your implementation time.

Reducer API

The Reducer API allows you to shrink an image based on the URL of the image. The image has to be available online in order to be shrunk via this API. You can call it from any programming language that allows you to send an HTTP POST request.

API call template

Calling method Parameters
POST

URL to call: https://api.shortpixel.com/v2/reducer.php

{"key": "your api key", "lossy": 1, "resize": 1, "resize_width": 1024, "resize_height": 1024, "cmyk2rgb": 1, "keep_exif": 0, "convertto": "+webp", "refresh": 0, "urllist": ["url1", "url2"]}

JSON Encoded parameters, as follows

  • key - Your API key.
  • lossy - 1 if we should compress the images(files) in a lossy way, 0 otherwise.
  • wait - maximum time to wait for the optimization to be ready.
  • resize - type of resize
  • resize_width - resize width in pixels
  • resize_height - resize height in pixels
  • cmyk2rgb - convert CMYK to RGB
  • keep_exif - keep the EXIF info of the file
  • convertto - conversion to other image formats
  • refresh - download the image again from source
  • urllist - list of image URLs to optimize.

API Parameters

Parameter Description
{key}

Your API key, as provided in your ShortPixel control panel and signup confirmation email.

{lossy}

Controls whether the image compression will use a lossy or lossless algorithm.

  • 1 - Lossy compression. Lossy has a better compression rate than lossless compression. The resulting image is not 100% identical with the original. Works well for photos taken with your camera.
  • 0 - Lossless compression. The shrunk image will be identical with the original and smaller in size. Use this when you do not want to loose any of the original image's details. Works best for technical drawings, clip art and comics.

{wait}

Set it between 1 and 30 to wait for that number of seconds for the conversion to be done before the API returns, 0 to return immediately. If the optimization is not done in the given amount of wait time, Code 1 (see below) is returned and you can just redo the same post later to find out if the image is ready.

{resize}

The type of resizing applied to the image.

  • 0 - no resizing, the current size is preserved.
  • 1 - outer resizing (image will contain the given resize_width x resize_height rectangle).
  • 3 means inner resizing (image will be contained in the given resize_width x resize_height rectangle).

{resize_width}

The width in pixels for the resize. Needed only if resize > 1.

{resize_height}

The height in pixels for the resize. Needed only if resize > 1.

{cmyk2rgb}

Convert CMYK to RGB, default is set to 1. Images for the web only need RGB format and converting them from CMYK to RGB makes them smaller.

{keep_exif}

Keep the EXIF tag of the image. Default is set to 0, meaning the EXIF tag is removed.

{convertto}

Convert also to other image types, when optimizing. Currently only WebP available (send "+wepb" as value for the parameter, or empty if no conversion needed).

{refresh}

If refresh is set to 1, the image is fetched again by our servers from the source and re-optimized. Otherwise, if the image is already optimized and still available on our servers, the currently optimized image info is returned.

{urllist}

The list of URLs where the original image is located. They need to be valid URLs and urlencoded.

API Return

The API call returns a JSON encoded data structure that shows the outcome of the call.

Field Meaning
Status Contains the status message for the call. The status itself is an object with two fields:
  • Code - This is a numeric code identifying the outcome of the call. Can be:
    • 1 - No errors, image scheduled for processing.
    • 2 - No errors, image processed, download URL available.
    • -102 - Invalid URL. Please make sure the URL is properly urlencoded and points to a valid image file.
    • -105 - URL is missing for the call.
    • -106 - URL is inaccessible from our server(s) due to access restrictions.
    • -107 - Too many URLs in a POST, maximum allowed has been exceeded.
    • -108 - Invalid user used for optimizing images from a particular domain.
    • -201 - Invalid image format.
    • -202 - Invalid image. The URL was valid but it did not point to an image.
    • -301 - The file is larger than the remaining quota.
    • -302 - The file is no longer available.
    • -303 - Internal API error: the file was not written on disk.
    • -401 - Invalid API key. Please check that the API key is the one provided to you.
    • -403 - Quota exceeded. You need to subscribe to a larger plan or to buy an additional one time package to increase your quota.
    • -500 - API is in maintenance mode. Please come back later.
  • Message - A text message explaining what the code stands for.
OriginalURL This is the original URL provided in the API call.
LossyURL Download URL for the optimized image using lossy compression.
LosslessURL Download URL for the optimized image using lossless compression.
OriginalSize Size of the original image
LossySize Size of the lossy compressed image
LoselessSize Size of the lossless compressed image.
Timestamp Timestamp of the file processing.

PHP Usage example

<?php
$URL = "https://api.shortpixel.com/v2/reducer.php";
$APIKey = "<YOUR API KEY HERE>";
$Lossy = "1";
$Resize = "1";
$ImagesList = array(
    "http://<FULL URL OF THE IMAGE1>",
    "http://<FULL URL OF THE IMAGE2>"
);
$ImagesList = array_map('utf8_encode', $ImagesList);
$Data = json_encode(array(
    "plugin_version" => "<YOUR DOMAIN HERE> 1",
    "key" => $APIKey,
    "lossy" => $Lossy,
    "urllist" => $ImagesList
));
$POSTArray = array(
    'http' => array(
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n" . "Content-Length: " . strlen($Data) ,
        'content' => $Data
        //http_build_query($Data),
        
    )
);
$Context = stream_context_create($POSTArray);
$Result = file_get_contents($URL, false, $Context);
?>
 


POST Reducer API

The POST Reducer API allows you to shrink an image that is not accessible online, by uploading it to our servers via a POST HTTP call. You can call it from any programming language that allows you to send an HTTP POST request.

Because you are sending the files along with the POST request, you need to create a multipart POST request (instead of a JSON request as in Reducer API's case) that contains the parameters and the files. The server answer has the same structure as the one from Reducer API, though.

API call template

Calling method Parameters
POST

URL to call: https://api.shortpixel.com/v2/post-reducer.php

The parameters are the same as for the Reducer API except the urllist that is replaced by either file_paths or file_urls and the posted files.

  • file_paths - the local file full paths.
  • file_urls - the corresponding OriginalURLs.

The parameters are sent as a multipart POST request, as in the following example (for PHP, see below a code snippet that generates a multipart POST request):

/
User-Agent: curl/7.21.2 (x86_64-apple-darwin)
Host: localhost:8080
Accept: */*
Content-Length: 1143
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------83ff53821b7c

------------------------------83ff53821b7c
Content-Disposition: form-data; name="key"

YOUR_20_CHARS_APIKEY
------------------------------83ff53821b7c--
Content-Disposition: form-data; name="lossy"

1
------------------------------83ff53821b7c--
Content-Disposition: form-data; name="file_paths"

{"file1": "/the/file1/path/a.png"}
------------------------------83ff53821b7c--
Content-Disposition: form-data; name="file1"; filename="a.png"
Content-Type: application/octet-stream

?PNG FILE CONTENTS HERE.....?
------------------------------83ff53821b7c
            

API Additional Parameters

Parameter Description
{file_paths}

The local file full paths as a json-encoded key-value array where the key is the same as the name of the file sent (file1 ...). You can provide any string but it should be unique to the file sent.

{file_urls}

The corresponding OriginalURLs sent by the API as answer to a previous call for the same filename. Please provide only either file_paths or file_urls.

API Return

The API call returns a JSON encoded data structure that shows the outcome of the call, similarily with the Reducer API return above. There are some additional fields and error codes, though:

Field Meaning
Status Contains the status message for the call. The status itself is an object with two fields:
  • Code - This is a numeric code identifying the outcome of the call. On top of the codes above, it can be:
    • -109 - The uploaded files are not present. If the urllist is present instead, the message asks use the Reducer API URL. The error will also be returned in case neither file_paths nor file_urls parameter si present.
    • -304 - Internal API Error - could not create user upload space. Please contact support if you encounter this error.
  • Message - A text message explaining what the code stands for.

PHP Multipart usage example

<?php
$URL = "https://api.shortpixel.com/v2/post-reducer.php";
$curl = curl_version();
$userAgent = "ShortPixel/1.0 " . " curl/" . $curl["version"];
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $URL);
curl_setopt_array($request, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_BINARYTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_USERAGENT => $userAgent,
));
$files = array(
    "file1" => "/path/to/first/file.jpg",
    "file2" => "/path/to/second/file.png"
);
$options = array(
    "key" => YOUR_SHORTPIXEL_API_KEY,
    "lossy" => 1,
    "file_paths" => json_encode($files);
);
curl_custom_postfields($request, $options, $files);
$response = curl_exec($request);
curl_close($request);

function curl_custom_postfields($ch, array $assoc = array() , array $files = array() , $header = array()) {
    // invalid characters for "name" and "filename"
    static $disallow = array(
        "\0",
        "\"",
        "\r",
        "\n"
    );
    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v) ,
        ));
    }
    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
                
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }
    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));
    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });
    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";
    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST => true,
        CURLOPT_BINARYTRANSFER => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body) ,
        CURLOPT_HTTPHEADER => array_merge(array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
            
        ) , $header) ,
    ));
}
              





Learn more
Cookies help us deliver our services. By using our services, you agree to use our cookies.