Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents


In this tutorial, I will show you how you can use Spreadshirt API v1 to create products with uploaded designs. I will first tell you about the preliminaries that need to be met in order to be able to create new products or upload designs. I will then tell you about the steps that need to be conducted to create a product with an uploaded design. And finally, I will show you in detail on code samples what exactly you need to do. Please note that I already described in general how to upload designs in "Uploading Designs to Spreadshirt using Spreadshirt API v1".

...

To create the design, you need to conduct a HTTP POST call on http https://api.spreadshirt.net/api/v1/shops/40000/designs for example.

Payload could be:

Code Block

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<design xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
        <name>Super cool design</name>
        <description>A super cool design</description>
</design>

Response contains HTTP Location header:

httphttps://api.spreadshirt.net/api/v1/shops/40000/designs/u100001143

Fetch the XML Data

To fetch the full XML data for the created design, you need to conduct a HTTP GET call on http https://api.spreadshirt.net/api/v1/shops/40000/designs/u100001143. This XML data contains for example the upload URL:

Code Block

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<design xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net" weight="0.0" xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/designs/u100001143" id="u100001143">
    <name>Super cool design</name>
    <description>A super cool design</description>
    <user xlink:href="httphttps://api.spreadshirt.net/api/v1/users/37508" id="37508"/>
    <restrictions>
        <fixedColors>false</fixedColors>
        <ownText>true</ownText>

        <obligatory>true</obligatory>
        <movable>true</movable>
        <targetView>0</targetView>
        <minimumScale>100</minimumScale>
        <visible>true</visible>
        <inverted>false</inverted>

    </restrictions>
    <size unit="px">
        <width>1016.0</width>
        <height>895.0</height>
    </size>
    <colors/>
    <printTypes>
        <printType xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/printTypes/1" id="1"/>
        <printType xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/printTypes/19" id="19"/>
        <printType xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/printTypes/17" id="17"/>
        <printType xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/printTypes/10" id="10"/>
        <printType xlink:href="httphttps://api.spreadshirt.net/api/v1/shops/40000/printTypes/21" id="21"/>
    </printTypes>
    <designCategories/>
    <price>
        <vatExcluded>0.00</vatExcluded>

        <vatIncluded>0</vatIncluded>
        <vat>19.00</vat>
        <currency xlink:href="httphttps://api.spreadshirt.net/api/v1/currencies/1" id="1"/>
    </price>
    <resources>
        <resource xlink:href="httphttps://image.spreadshirtspreadshirtmedia.net/image-server/v1/designs/100001143" type="preview" mediaType="png"/>
<!-- upload url !!! -->
        <resource xlink:href="httphttps://image.spreadshirtspreadshirtmedia.net/image-server/v1/designs/100001143" type="montage" mediaType="png"/>
    </resources>
    <created>2010-08-02T08:29:59Z</created>
</design>

...

From the fetched XML file, you need to extract the image API URL from design/resources/resource@type=montage. In our example, this is httphttps://image.spreadshirtspreadshirtmedia.net/image-server/v1/designs/100001143.

Upload the Pixel Design

To upload the pixel design, you need to conduct a HTTP PUT call on httphttps://image.spreadshirtspreadshirtmedia.net/image-server/v1/designs/100001143 and upload a PNG design similar to the following one:

...

To create the product, you need to conduct a HTTP POST call on httphttps://api.spreadshirt.net/api/v1/shops/40000/products for example.  Make sure that you set the design id correctly under product/configurations/configuration/content/svg/image@designId=100001143.

Payload could be: 

Code Block

<product xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
    <productType id="6"/>
    <appearance id="1"/>
    <restrictions>
        <freeColorSelection>false</freeColorSelection>
        <example>false</example>
    </restrictions>
    <configurations>
        <configuration type="design">
            <printArea id="4"/>
            <printType id="1"/>
            <offset unit="mm">
                <x>60.0</x>
                <y>70.0</y>
            </offset>
            <content dpi="25.4" unit="mm">
                <svg>
<!-- use upload design id here -->
                    <image transform="" width="200.025" height="194.945" printColorIds="1" designId="u100001143"/>
                </svg>
            </content>
            <restrictions>
                <changeable>false</changeable>
            </restrictions>
        </configuration>
    </configurations>
</product>

Response contains HTTP Location header of the created product:

httphttps://api.spreadshirt.net/api/v1/shops/40000/products/100005555

In your code, use your shop id to upload designs and create products for your shop!

Code

Java

Code Block

public class ProductCreation {
    private static final Logger log = LoggerFactory.getLogger(ProductCreation.class);

    public static final String API_KEY = "...";
    public static final String SECRET = "...";

    public static final String UPLOAD_URL = "httphttps://api.spreadshirt.net/api/v1/shops/40000/designs";
    public static final String UPLOAD_XML = "./src/main/resources/productcreation/design.xml";
    public static final String UPLOAD_IMAGE = "./src/main/resources/productcreation/design.png";
    public static final String CREATION_URL = "httphttps://api.spreadshirt.net/api/v1/shops/40000/products";
    public static final String PRODUCT_XML = "./src/main/resources/productcreation/product.xml";

    public static void main(String[] args)
            throws Exception {
        HttpUrlConnectionFactory urlConnectionFactory =
                new HttpUrlConnectionFactory(API_KEY, SECRET, null);
        HttpCallCommandFactory commandFactory =
                new HttpCallCommandFactory(urlConnectionFactory);

        // create design data using xml
        HttpCallCommand createDesignCommand =
                commandFactory.createPlainHttpCallCommand(UPLOAD_URL, HttpMethod.POST, null);
        createDesignCommand.setInput(getXMLData(UPLOAD_XML));
        createDesignCommand.setApiKeyProtected(true);
        createDesignCommand.execute();
        if (createDesignCommand.getStatus() >= 400) {
            throw new Exception("Could not create design xml!");
        }
        log.info("XML location is: " + createDesignCommand.getLocation());

        // get created design xml
        HttpCallCommand getDesignCommand =
                commandFactory.createPlainHttpCallCommand(createDesignCommand.getLocation(), HttpMethod.GET, null);
        getDesignCommand.execute();
        if (createDesignCommand.getStatus() >= 400) {
            throw new Exception("Could not retrieve design xml from " + createDesignCommand.getLocation() + "!");
        }
        String message = (String) getDesignCommand.getOutput();

        // determine upload location
        String searchString = "resource xlink:href=\"";
        int index = message.indexOf(searchString);
        String uploadUrl = message.substring(index + searchString.length(),
                message.indexOf("\"", index + searchString.length() + 1));
        log.info("Upload location is: " + uploadUrl);

        // upload image
        HttpCallCommand uploadDesignCommand =
                commandFactory.createFileHttpCallCommand(uploadUrl, HttpMethod.PUT, null, new File(UPLOAD_IMAGE), null);
        uploadDesignCommand.setApiKeyProtected(true);
        uploadDesignCommand.execute();
        if (uploadDesignCommand.getStatus() >= 400) {
            log.error(uploadDesignCommand.getErrorMessage());
            throw new Exception("Status above 400 expected but status was " + uploadDesignCommand.getStatus() + "!");
        }

        // create product data using xml
        HttpCallCommand createProductCommand =
                commandFactory.createPlainHttpCallCommand(CREATION_URL, HttpMethod.POST, null);
        String productData = getXMLData(PRODUCT_XML);
        // use id from fetched design xml here -> my solution is only a hack
        productData = productData.replace("THE_DESIGN_ID", "u" + uploadUrl.substring(uploadUrl.lastIndexOf('/') + 1));
        createProductCommand.setInput(productData);
        createProductCommand.setApiKeyProtected(true);
        createProductCommand.execute();
        if (createProductCommand.getStatus() >= 400) {
            throw new Exception("Could not create product xml!");
        }
        log.info("XML location is: " + createProductCommand.getLocation());
    }

    private static String getXMLData(String fileName)
            throws IOException {
        ByteArrayOutputStream os = null;
        InputStream is = null;
        try {
            os = new ByteArrayOutputStream();
            is = new FileInputStream(new File(fileName));
            int length = 0;
            byte[] data = new byte[4096];
            while ((length = is.read(data)) != -1) {
                os.write(data, 0, length);
            }
            return os.toString();
        } finally {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        }
    }
}

You can find the sample code on SourceForge's spreadshirtapps project at https://spreadshirtapps.svn.sourceforge.net/svnroot/spreadshirtapps/java/tutorials.

PHP

Code Block

  <?php
    // This product creation script shows you how to create new products on the
    // Spreadshirt platform using Spreadshirt API v1.

    $productTypeId = "6";
    $printTypeId = "14";
    $printColorIds = "13,20";
    $productTypeAppearanceId = "1";
    $productTypePrintAreaId = "4";
    $designId = "m2484607-1";

    // 1. Get shop data
    $shopUrl = "httphttps://api.spreadshirt.net/api/v1/shops/205909";
    $ch = curl_init($shopUrl);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $result = curl_exec($ch);
    // Close the handle
    curl_close($ch);

    $shop = new SimpleXMLElement($result);
    $namespaces = $shop->getNamespaces(true);

    // 2. Get product type data
    $attributes = $shop->productTypes->attributes($namespaces['xlink']);
    $productTypeUrl = $attributes->href . "/" . $productTypeId;
    $ch = curl_init($productTypeUrl);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $result = curl_exec($ch);
    // Close the handle
    curl_close($ch);

    $productType = new SimpleXMLElement($result);

    // 3. Get design data
    $attributes = $shop->designs->attributes($namespaces['xlink']);
    $designUrl = $attributes->href . "/" . $designId;
    $ch = curl_init($designUrl);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $result = curl_exec($ch);
    // Close the handle
    curl_close($ch);

    $design = new SimpleXMLElement($result);

    // 4. Prepare product
    // get positioning data for selected product type
    $printArea = null;
    foreach ($productType->printAreas->printArea as $current) {
        if ($current['id'] == $productTypePrintAreaId) {
            $printArea = $current;
        }
    }

    $product = new SimpleXMLElement(getFileData("product.xml"));
    $product->productType['id'] = $productTypeId;
    $product->appearance['id'] = $productTypeAppearanceId;
    $configuration = $product->configurations->configuration;
    $configuration->printArea['id'] = $productTypePrintAreaId;
    $configuration->printType['id'] = $printTypeId;
    $configuration->offset->x =
              ((doubleval($printArea->boundary->size->width) - doubleval($design->size->width)) / 2);
    $configuration->offset->y =
              ((doubleval($printArea->boundary->size->height) - doubleval($design->size->height)) / 4);
    $image = $product->configurations->configuration->content->svg->image;
    $image['width'] = $design->size->width;
    $image['height'] = $design->size->height;
    $image['designId'] = $designId;
    $image['printColorIds'] = $printColorIds;

    // 5. Create product
    $attributes = $shop->products->attributes($namespaces['xlink']);
    $productsUrl = $attributes->href;

    $header = array();
    $header[] = createSprdAuthHeader("POST", $productsUrl);
    $header[] = "Content-Type: application/xml";

    $ch = curl_init($productsUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $product->asXML());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    $result = curl_exec($ch);
    // Close the handle
    curl_close($ch);

    $productUrl = parseHttpHeaders($result, "Location");

    $ch = curl_init($productUrl);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $result = curl_exec($ch);
    // Close the handle
    curl_close($ch);

    $product = new SimpleXMLElement($result);
    $resource = $product->resources->resource[0];
    $attributes = $resource->attributes($namespaces['xlink']);

    echo '<html><body>';
    echo 'Product available at: <a href="' . $productUrl . '">' . $productUrl . '</a></br>';
    echo 'Product image is available at: <a href="' . $attributes->href . '">' . $attributes->href . '</a></br>';
    echo '<img src="' . $attributes->href . '?width=1000"/>';
    echo '</body></html>';

    function createSprdAuthHeader($method, $url) {
        $apiKey = x"your key ...";
        $secret = x"your secret ...";
        $time = time()*1000;

        $data = "$method $url $time";
        $sig = sha1("$data $secret");

        return "Authorization: SprdAuth apiKey=\"$apiKey\", data=\"$data\", sig=\"$sig\"";
    }

    function parseHttpHeaders( $header, $headername ) {
        $retVal = array();
        $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
        foreach( $fields as $field ) {
            if( preg_match('/('.$headername.'): (.+)/m', $field, $match) ) {
                return $match[2];
            }
        }
        return $retVal;
    }

    function getFileData($file) {
        $fp = fopen($file, "r");
        $data = "";
        while(!feof($fp)) {
            $data .= fgets($fp, 1024);
        }
        fclose($fp);
        return $data;
    }
?>

...